注册 登录
编程论坛 C语言论坛

局部变量传参的疑惑

taking 发布于 2021-10-22 19:00, 1380 次点击
程序代码:

void initArr(int i[3]) {
    printf(" %d ", i[0]);// 打印结果10
    i[0] = 100;
    printf(" %d ", i[0]);// 打印结果100
}
void test2() {
    int i[3] = { 10,20,30 };
    initArr(i);
    printf(" %d ", i[0]);// 打印结果100
}

为什么我这个主调函数test2()中的局部变量i, 传递给initArr,在initArr中修改i的内容,主调函数也会受到影响?
initArr中的I不该是独立栈空间新开辟的局部变量吗?照说不是只有地址传递用指针接收才能达到这效果吗?
学多级指针的时候老师说,传参相当与赋值.被调函数会自己开辟空间存放变量.
从语法角度说,如果传I就是传递地址,那么被调函数定义形参的时候不应该需要一个指针去间接引用吗?
还是说就单纯的把这个情况看成是语法糖?
2 回复
#2
自由而无用2021-10-22 19:25
Can I re-describe your question like this ?
whats the difference between the function prototype
void initArr(int i[3])
and
void initArr(int *i)
-------------------------gcc answer-------------------
no difference (maybe its a standard ?)
-------------------------the reason-------------------
gcc generates same code
-------------------------how to try-------------------
//online parser: https://www.bccn.net/run/
程序代码:
#include <stdio.h>
#include <stdlib.h>

//#define ARG_TYPE
#ifdef ARG_TYPE
void initArr(int i[3])
#else
void initArr(int *i)
#endif
{
    printf("sub[i] = %d\n", i[0]);
    i[0] = 100;
    printf("sub[i] = %d\n", i[0]);
}

int main(int argc, char *argv[])
{
    int i[3] = {10, 20, 30};
   
    initArr(i);

    printf("main[i] = %d\n", i[0]);
   
    system("gcc *.c -o v.out");
#ifdef ARG_TYPE
    system("objdump -d v.out > a.txt");
    system("cat a.txt");
#else
    system("objdump -d v.out > b.txt");
    system("cat b.txt");
#endif
    system("diff a.txt b.txt");

    return 0;
}


output sample:
......
<   4004ef:    49 c7 c0 20 07 40 00     mov    $0x400720,%r8
<   4004f6:    48 c7 c1 b0 06 40 00     mov    $0x4006b0,%rcx
---
>   4004ef:    49 c7 c0 30 07 40 00     mov    $0x400730,%r8
>   4004f6:    48 c7 c1 c0 06 40 00     mov    $0x4006c0,%rcx
......

So, finally you will find that nothing is different except the dynamic address
#3
taking2021-10-22 19:55
Thanks,quite clear,good good study,day day up!
#4
rjsp2021-10-22 20:56
局部变量i, 传递给initArr,在initArr中修改i的内容
不,你没有修改i的内容,你修改的是i指向的内容。
1