a和&a在C中作为函数参数传递的数组不同
发布时间:2020-12-16 04:53:21 所属栏目:百科 来源:网络整理
导读:为什么a和 a的值对于作为函数参数传递的数组有所不同?对于在函数体内定义的数组,b和 b没有区别.代码如下: void foo(int a[2]){ int b[2]; printf("%p %pn",a,a); printf("%p %pn",b,b);}int main(){ int a[2]; foo(a); return 0;} 编辑: 因此,经过所有
为什么a和& a的值对于作为函数参数传递的数组有所不同?对于在函数体内定义的数组,b和& b没有区别.代码如下:
void foo(int a[2]) { int b[2]; printf("%p %pn",a,&a); printf("%p %pn",b,&b); } int main() { int a[2]; foo(a); return 0; } 编辑: 在main()中: int a[2]; /* define an array. */ foo(a); /* 'a' decays into a pointer to a[0] of type (int*). */ /* since C is pass-by-value,this pointer is replicated and */ /* a local copy of it is stored on the stack for use by foo(). */ 在foo()中: printf("%p %pn",&a); /* 'a' is the value of the pointer that has been replicated,*/ /* and it points to 'a[0]' in main() */ /* '&a' is the address of the replicated pointer on the stack. */ /* since the stack grows from higher to lower addresses,*/ /* the value of '&a' is always lower than a. */ 解决方法
基本上当你输入void foo(int a [2])时,你正在以一种有趣的方式写入void foo(int * a).
我必须从标准中查找特定的引用,但是当正在分析函数签名时,类型为T的N个元素的类型数组的参数将转换为指向T的指针.当您稍后键入foo(a)时,衰减成指向第一个元素的地址的指针,该元素被复制.在foo中,您将指针的值与主数组a的第一个元素的值与foo中指针a的地址进行比较. 另一方面,在同一个函数中,当数组在foo内的b范围内时,数组的地址(& b)和数组的第一个元素的地址(可以通过强制衰减获得)通过键入b)是相同的地址. 未来的两条简单信息: >函数签名中的数组被解释为指针:避免使用该语法并使用指针语法,您将获得更少的惊喜 例: void foo( int a[2] ); // void foo( int *a ); int main() { int x[2]; foo( x ); // foo( &x[0] ); -- inside foo,a is a copy of &x[0] printf( "%dn%dn",(int)&a,(int)a ); // &a[0] which is the same address as &a // (different type though) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |