#include <stdlib.h>
double* convertTemperature(double celsius, int* returnSize) {
double* ans = (double*)malloc(2 * sizeof(double)); // 动态分配内存以存储两个温度值
if (ans == NULL) {
*returnSize = 0;
return NULL;
}
ans[0] = celsius + 273.15; // 计算开尔文温度并存储在ans[0]中
ans[1] = celsius * 1.80 + 32.00; // 计算华氏温度并存储在ans[1]中
*returnSize = 2; // 返回数组的大小
return ans;
}
int main() {
int returnSize;
double celsius = 25.0;
double* temperature = convertTemperature(celsius, &returnSize);
if (temperature != NULL) {
printf("开尔文温度: %.2f\n", temperature[0]);
printf("华氏温度: %.2f\n", temperature[1]);
free(temperature); // 释放动态分配的内存
}
return 0;
}
在上面的代码中,returnSize
是一个指向整数的指针,用于存储返回的数组的大小。在convertTemperature
函数中,通过修改returnSize
指向的整数值来告知调用者返回的数组大小。这样可以在调用函数后获取返回数组的大小,以便正确地访问数组中的元素。
在main
函数中,我们声明一个整数变量returnSize
,并将其传递给convertTemperature
函数。在函数内部,我们通过修改returnSize
的值来告知调用者返回的数组大小为2。这样,我们就可以在main
函数中知道返回的数组大小,并正确地访问数组中的元素。
这种通过指针参数传递数组大小的方式可以有效地将额外的信息传递给调用者,使得调用者能够正确地处理返回的数组。