C编码: For loop/call by reference confusion

标签 c

在这个程序中,我不太明白注释下面发生了什么:/*pass the array */。该程序的输出应该是输入温度 #0,#1,#2.....#30 的 31 次迭代,然后将这些用户输入的值转换为摄氏度。我的困惑在于函数调用 Convert(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.2f\n", 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数组第一个元素的指针,然后修改其元素。换句话说,数组永远不会被复制。由于只传递了一个指针,因此无法知道形式参数 heatconvert 中存在多长时间。因此,最好也传递数组的长度。我将这样做:

#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 input\n");
            exit(EXIT_FAILURE);
        }
    }

    convert(temps, LEN(temps));

    for (i = 0; i < LEN(temps) ; i++) {
        printf("%6.2f\n", temps[i]);
    }

    return 0;
}

关于C编码: For loop/call by reference confusion,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40882522/

相关文章:

无法在Linux中使用Eclipse构建C项目

C编程。使用 execl 和 pthread

c - 为什么我的程序不在 C 中打印真实结果

c++ - 在 Netbeans 中从 header 切换到 cpp 文件?

c++ - X11 具有 undefined reference 的功能,但似乎没问题。 IDE 不会提示那些库

c - 在 C unix 中从外部文件(或控制文件)管道传输两个文件

c - 一些函数在较新的编译器中不起作用

c - 使用 scanf() 处理过度输入

c - 通过 c/libcurl 使用有效密码访问受密码保护的新闻网站

c - OpenSSL ASN.1 编程教程