微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

为什么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' 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( "%d\n%d\n",(int)&a,(int)a ); // &a[0] which is the same address as &a
                                          // (different type though)
}

原文地址:https://www.jb51.cc/c/119980.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐