我有以下代码:
int main(){
int tab[5]={10, 20, 30, 40, 50};
int *ptr;
ptr=tab+4;
printf("%d,%#x,%#x. \n",*ptr-1,&tab,ptr);
return 0;}
“tab”位于从地址0x28FEF8开始的内存区域。
我知道*ptr-1的值为49,&tab的值为0x28FEF8。
有人可以解释一下为什么“ptr”的值为0x28FF08吗?我猜测它会是 0x28FEFC。
提前谢谢您!
最佳答案
如果我们“绘制”您的数组,因为它在内存中布局,它将看起来像这样
+----+----+----+----+----+ | 10 | 20 | 30 | 40 | 50 | +----+----+----+----+----+
Then you need to remember that arrays naturally decays to pointers to their first element, i.e. tab
is equal to &tab[0]
. And then you need to remember that for any array or pointer a
and index i
, the expression a[i]
is exactly equal to *(a + i)
. From that it's easy to deduce that tab + 4
is equal to &tab[4]
, i.e. a pointer to the fifth element.
So if we again draw the array, but now with pointers:
+----+----+----+----+----+ | 10 | 20 | 30 | 40 | 50 | +----+----+----+----+----+ ^ ^ | | &tab[0] &tab[4] | &tab
If &tab[0]
is equal to 0x28fef8
then &tab[4]
is equal to 0x28fef8 + sizeof(int) * 4
, as it is pointing to index 4 of an int
array, and it's indeed 0x28ff08
.
Please note that while &tab[0]
and &tab
are pointing to the same location, they are semantically different. &tab[0]
is a pointer to a single elements and is of type int *
, while &tab
is a pointer to the array and is of type int (*)[5]
.
On a related note, the correct format to print void *
pointers is "%p"
. So your printing should really be
printf("%d,%p,%p. \n", *ptr-1, (void *) &tab, (void *) ptr);
请注意,确实需要强制转换为 void *
。
关于c - 知道初始地址的指针的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50711244/