【问题标题】:Question on arrays getting passed through a function关于数组通过函数传递的问题
【发布时间】:2023-01-08 13:48:03
【问题描述】:

我正在学习变量是如何按值传递给函数的,而数组是按引用传递的。

我运行我的脚本来验证这一点,但是指针地址不同。这是为什么?

void arrayFunction(int array[4]);

int main(void){
    int foo[4] = {0, 1, 2, 3};
    printf("This is the address to foo in main: %p\n",&foo);
    arrayFunction(foo);
}

void arrayFunction(int array[4]){
    printf("This is the address to array in method: %p\n", &array);
    array[0] = 22;
}



【问题讨论】:

    标签: c


    【解决方案1】:

    如果函数参数声明为指针(而不是数组),则数组参数只会衰减为指针。

    这是您的程序的修改版本,显示:

    #include <stdio.h>
    void arrayFunction(int array[4]);
    
    int main(void){
        int foo[4] = {0, 1, 2, 3};
        printf("This is the address to foo in main:     %p
    ",&foo);
        arrayFunction(foo);
    }
    
    void arrayFunction(int *array){ // <-- note the argument declaration
        printf("This is the address to array in method: %p
    ", array);
        array[0] = 22;
    }
    

    【讨论】:

      猜你喜欢
      • 2022-12-04
      • 2011-09-29
      • 1970-01-01
      • 2011-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-21
      • 1970-01-01
      相关资源
      最近更新 更多