C 编码:用于循环/引用调用混淆



在这个程序中,我不太明白评论下面发生了什么:/*传递数组 */。该程序的输出应该是输入温度#0,#1,#2.....#30的31次迭代,然后将用户输入的值转换为摄氏度。我的困惑在于函数调用转换(temps)的目的或工作方式,以及它下面的所有内容如何作为一个整体运行。

任何关于代码如何"工作"以实现所述输出的澄清都会很棒。此外,通过引用在转换函数中发生的调用,如果是这样,有人可以解释其中的动态。

谢谢。

#define COUNT 31
void convert (float heat[]);
void main()
{
float temps[COUNT];
int index;
/*load the array with values*/
for (index = 0; index < COUNT ; index++)
{
printf("Enter temperature #%d: ", index);
scanf("%f", &temps[index]);
}
/*pass the array */
convert(temps);
for (index = 0; index < COUNT ; index++)
printf("%6.2fn", temps[index]);
}
/*******************convert function ************************/
void convert (float heat[])
{
int index;
for (index = 0; index < COUNT; index++)
{
heat[index] = (5.0/9.0)*(heat[index]-32);
}
}

函数 convert接收指向temps数组的第一个元素的指针,然后修改其元素。换句话说,永远不会复制数组。由于只传递了一个指针,因此无法判断形式参数heat转换过程中的时间。因此,传递数组的长度也是一个好主意。以下是我将如何做到这一点:

#include <stdio.h>
#include <stdlib.h>
#define LEN(arr) ((int) (sizeof (arr) / sizeof (arr)[0]))
void convert(float heat[], int heatLen)
{
int i;
for (i = 0; i < heatLen; i++) {
heat[i] = (5.0 / 9.0) * (heat[i] - 32);
}
}

int main(void)
{
float temps[31];
int i, nRead;
for (i = 0; i < LEN(temps) ; i++) {
printf("Enter temperature #%d: ", i);
nRead = scanf("%f", &temps[i]);
if (nRead != 1) {
fprintf(stderr, "Invalid inputn");
exit(EXIT_FAILURE);
}
}
convert(temps, LEN(temps));
for (i = 0; i < LEN(temps) ; i++) {
printf("%6.2fn", temps[i]);
}
return 0;
}

C 中没有call by reference这样的东西。该语言支持按值调用。

电话会议

convert(temps);

传递一个。由于temps是一个数组,因此它确实通过了address of the first element in the array。对于函数,它看起来像一个pointer to float- 我们说数组在用作函数参数时会衰减为指针。

convert函数中,您可以使用传递的地址值(即使用指针)更改数组中元素的值。这可以通过简单的索引来完成,例如

temps[i] = .....;

*(temps + i) = ....;

最新更新