为什么作为函数参数传递的数组的a和&a值不同?对于在函数体中定义的数组,b和&b没有区别。代码如下:
void foo(int a[2])
{
int b[2];
printf("%p %p\n", a, &a);
printf("%p %p\n", 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 %p\n", a, &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] )
时,你的写作方式很有趣。
我必须从标准中查找特定的引号,但是在分析函数签名时,t类型的n个元素的数组类型的参数将转换为指向t的指针。当您稍后键入void foo( int *a )
,foo(a)
时,会衰减为指向第一个元素的地址的指针,该指针将被复制。在a
中,您将比较指向foo
中数组第一个元素的指针的值与a
中指针的地址。
另一方面,在同一函数中,当数组与main
内的a
在作用域内时,数组的地址(foo
)和数组的第一个元素的地址(可以通过键入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( "%d\n%d\n", (int)&a, (int)a ); // &a[0] which is the same address as &a
// (different type though)
}