a和&a在C中作为函数参数传递的数组不同

nit*_*tzs 7 c arrays

为什么作为函数参数传递的数组的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;
}
Run Code Online (Sandbox Code Playgroud)

编辑:
所以,经过所有的讨论,我了解到以下情况:

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(). */
Run Code Online (Sandbox Code Playgroud)

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. */
Run Code Online (Sandbox Code Playgroud)

Dav*_*eas 10

基本上当你打字的时候,void foo( int a[2] )你会以一种有趣的方式写作void foo( int *a ).

我必须从标准中寻找特定的引用,但是当正在分析函数签名时,类型为T的N个元素的类型数组的参数被转换为指向T的指针.当您稍后键入时foo(a),a衰减为指向第一个元素的地址的指针,该元素被复制.内部foo您的指针数组的第一元素的值进行比较amain与所述指针的地址afoo.

另一方面,在同一个函数中,当数组在作为b内部的范围内时foo,array(&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( "%d\n%d\n", (int)&a, (int)a ); // &a[0] which is the same address as &a
                                          // (different type though)
}
Run Code Online (Sandbox Code Playgroud)