Is an array name a pointer?

2018-12-30 22:38发布

Is an array's name a pointer in C? If not, what is the difference between an array's name and a pointer variable?

9条回答
余生无你
2楼-- · 2018-12-30 23:38

The array name by itself yields a memory location, so you can treat the array name like a pointer:

int a[7];

a[0] = 1976;
a[1] = 1984;

printf("memory location of a: %p", a);

printf("value at memory location %p is %d", a, *a);

And other nifty stuff you can do to pointer (e.g. adding/substracting an offset), you can also do to an array:

printf("value at memory location %p is %d", a + 1, *(a + 1));

Language-wise, if C didn't expose the array as just some sort of "pointer"(pedantically it's just a memory location. It cannot point to arbitrary location in memory, nor can be controlled by the programmer). We always need to code this:

printf("value at memory location %p is %d", &a[1], a[1]);
查看更多
余生无你
3楼-- · 2018-12-30 23:38

The array name behaves like a pointer and points to the first element of the array. Example:

int a[]={1,2,3};
printf("%p\n",a);     //result is similar to 0x7fff6fe40bc0
printf("%p\n",&a[0]); //result is similar to 0x7fff6fe40bc0

Both the print statements will give exactly same output for a machine. In my system it gave:

0x7fff6fe40bc0
查看更多
梦该遗忘
4楼-- · 2018-12-30 23:39

Array name is the address of 1st element of an array. So yes array name is a const pointer.

查看更多
登录 后发表回答