数组名称如何包含其地址以及其中的第一个元素? [英] How array name has its address as well as its first element in it?

查看:124
本文介绍了数组名称如何包含其地址以及其中的第一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输出:

a=1606416992, &a=1606416992,
*a=1, &(*a)=1606416992

程序:

#include "stdio.h"
main()
{
    int a[4]={1,2,3,4};
    printf("a=%u, &a=%u, *a=%d, &(*a)=%u\n",a,&a,*a,&(*a));
}

我知道数组名称是指向数组第一个元素的指针. 但是我的疑问是指针应该存储在某个地方,并且应该有一个地址位置. 如果是这样,那么如何在位置"1606416992"存储元素"1",并且指向数组的指针的地址位置是相同的"1606416992"?

I know array name is the pointer to first element of the array. But my doubt is pointer should be stored somewhere and it should have an address location. If so how come at location "1606416992" element "1" is stored and same "1606416992" is the address location of pointer to array?

请帮助澄清.

推荐答案

在表达式中使用数组名称时,它会变成指向第一个元素的指针.但是,此规则有3个例外:

An array name decays into a pointer to the first element when used in an expression. However, there are 3 exceptions to this rule:

  • 该数组显示为sizeof();
  • 的操作数
  • 使用&运算符获取阵列的地址;
  • 该数组是一个字符串或宽字符串文字初始值设定项.
  • The array appears as the operand of sizeof();
  • The array's address is taken with the & operator;
  • The array is a string or wide-string literal initializer.

在您的代码中,a&(*a)是同一事物,因为*a等同于a[0],因此,&(*a)a是相同的地址.

In your code, both a and &(*a) are the same thing, since *a is equivalent to a[0], thus, &(*a) is the same address as a.

&aa具有相同的地址,因为使用&时,数组不会衰减为指针.因此,&a表示数组的地址,即可以找到第一个元素的地址.使用&a时,您无需获取指向第一个元素的指针的地址,而获取数组的地址,因为在这种特殊情况下,a并非指向第一个元素的指针.

&a has the same address as a because with &, the array does not decay into a pointer. Therefore, &a denotes the address of the array, namely, the address where the first element can be found. With &a, you're not taking the address of pointer to first element, you're taking the address of the array, since a is not a pointer to first element in that special case.

编辑 如其他答案所述,在转换为void *后,应使用%p打印指针值:

EDIT As mentioned in other answers, you should use %p to print pointer values, after casting to void *:

printf("a=%p, &a=%p, *a=%d, &(*a)=%p\n",(void *) a, (void *) &a,*a,(void *) &(*a));

这篇关于数组名称如何包含其地址以及其中的第一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆