[英]Different Pointer Arithmetic Results when Taking Address of Array
程序:
#include<stdio.h>
int main(void) {
int x[4];
printf("%p\n", x);
printf("%p\n", x + 1);
printf("%p\n", &x);
printf("%p\n", &x + 1);
}
輸出:
$ ./a.out
0xbff93510
0xbff93514
0xbff93510
0xbff93520
$
我希望以下是上述程序的輸出。 例如:
x // 0x100
x+1 // 0x104 Because x is an integer array
&x // 0x100 Address of array
&x+1 // 0x104
但是最后一個陳述的輸出與我預期的不同。 &x
也是數組的地址。 因此,在此處遞增1將打印地址遞增4.但是&x+1
表示地址遞增10.為什么?
x -> Points to the first element of the array.
&x ->Points to the entire array.
偶然發現了一個描述性的解釋: http : //arjunsreedharan.org/post/69303442896/the-difference-between-arr-and-arr-how-to-find
SO鏈接: 為什么arr和&arr一樣?
在情況4中,您得到0x100 + sizeof x
而sizeof x
是4 * sizeof int
= 4 * 4 = 16 = 0x10。
(在您的系統上, sizeof int
為4)。
評估這個問題的簡單方法是:
增量上的任何指針都指向其基類型的下一個內存位置。
這里&x的基類型是int(* p)[4] ,它是指向4個整數數組的指針 。
因此,此類型的下一個指針將指向原始數組的16個字節(假設int為4個字節)。
即使x
和&x
評估為相同的指針值,它們也是不同的類型。 衰減到指針后的x
類型是int*
而&x
類型是int (*)[4]
。
sizeof(x)
是sizeof(int)*4
。
因此, &x
和&x + 1
之間的數值差是sizeof(int)*4
。
使用2D陣列可以更好地可視化。 假設你有:
int array[2][4];
array
的內存布局是:
array
|
+---+---+---+---+---+---+---+---+
| | | | | | | | |
+---+---+---+---+---+---+---+---+
array[0] array[1]
| |
+---+---+---+---+---+---+---+---+
| | | | | | | | |
+---+---+---+---+---+---+---+---+
如果你使用指向這樣一個數組的指針,
int (*ptr)[4] = array;
並通過指針查看內存,它看起來像:
ptr ptr+1
| |
+---+---+---+---+---+---+---+---+
| | | | | | | | |
+---+---+---+---+---+---+---+---+
如您所見, ptr
和ptr+1
之間的差異是sizeof(int)*4
。 這個類比適用於代碼中&x
和&x + 1
之間的差異。
信不信由你,程序的行為是不確定的 !
&x + 1
實際上是指向正好超出了數組,@ 1486的答案巧妙地指出。 你沒有那段記憶。 即使嘗試為其指定指針也是未定義的行為,更不用說嘗試取消引用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.