的输出a
并&a
保持相同的值。但是,它们因类型而异。
a
对具有类型“ ”的引用,pointer to type
但&a
它是“ pointer-to-array-of-n-type
”,其中n
是数组的大小。
让我们尝试在下面的代码中理解相同的内容:
#include <stdio.h>
int main()
{
int a[4]={1,2,3,4};
int *ptr1=a;
int (*ptr2)[4]=&a;
printf("a points to first element of array :%p\n",(void*)a);
printf("&a points to whole array. Start address is same as 'a': %p\n",(void*)&a);
printf("Incrementing 'a' steps to the next element in array New Value: %p\n",(void*)(a+1));
printf("Incrementing '&a' steps over the entire array. New Value: %p\n",(void*)(&a+1));
printf("ptr1: %p, ptr2:%p\n",(void*)ptr1,(void*)ptr2);
return 0;
}
输出:
a points to first element of array :0x7fff3da3d560
&a points to whole array. Start address is same as 'a': 0x7fff3da3d560
Incrementing 'a' steps to the next element in array New Value: 0x7fff3da3d564
Incrementing '&a' steps over the entire array. New Value: 0x7fff3da3d570
ptr1: 0x7fff3da3d560, ptr2:0x7fff3da3d560
ptr1
是类型:指向整数的指针。在这个程序中,定义为指向数组名的指针。因此,保存数组第一个元素的地址。ptr1 = &a[0]
ptr2
是类型:指向 4 个整数数组的指针。在这个程序中,定义为指向整个数组的指针。递增ptr2
导致它跨过整个阵列。通常仅在使用数组数组操作时有用。
可视化数组的存储a
:
+-----------------+-----------------+-----------------+-----------------+
| 1 | 2 | 3 | 4 |
+-----------------+-----------------+-----------------+-----------------+
0x7fff3da3d560 0x7fff3da3d564 0x7fff3da3d568 0x7fff3da3d56c 0x7fff3da3d570
▲ ▲ ▲ ▲ ▲ ▲ ▲ ▲
| | | | | | | |
|(a) | | (a + 1) | | |
| (ptr1) | (ptr1 + 1) | (ptr2 + 1)
|------------|----------------------------------------------------------|
| | |
| (ptr2) |
| |
(&a) = 0x7fff3da3d560 (&a + 1) = 0x7fff3da3d570