[英]Pointer to an entire array
我偶然發現了“指向整個數組的指針”並編寫了一個測試程序來清除一些東西:
#include <stdio.h>
int main(){
int x[5] = {1, 2, 3, 4, 5};
int *a = x; // points to the 1st array element
int (*b)[5] = &x; // points to the 1st addres of the stream of 5 int elements
int (*c)[5] = x; // points to the 1st addres of the stream of 5 int elements
printf("%p\n%p\n%p\n\n",
(void *)a,
(void *)b,
(void *)c
);
++a;
++b;
++c;
printf("%p\n%p\n%p\n\n",
(void *)a,
(void *)b,
(void *)c
);
return 0;
}
這輸出:
0x7ffed0c20690
0x7ffed0c20690
0x7ffed0c20690
0x7ffed0c20694
0x7ffed0c206a4
0x7ffed0c206a4
對我來說,它看起來像線條:
int (*b)[5] = &x;
int (*c)[5] = x;
達到完全相同的結果,因為:
它們分配相同的地址(在*b
的情況下,它是整個數組的地址,在*c
的情況下,它是第一個數組成員的地址,但這兩個重疊)和
為*b
和*c
分配相同大小的 5 · int
指針,這在我增加值時會導致完全相同的指針算術。
Q1:我遺漏的*b
和*c
的定義之間是否存在任何隱藏的差異?
Q2:指針算術是否只取決於指針的大小?
在你指出之后,我注意到我確實收到了一個錯誤:
main.c:9:16: warning: initialization of ‘int (*)[5]’ from incompatible pointer type ‘int *’ [-Wincompatible-pointer-types]
int (*c)[5] = x; // points to the 1st array element
Q1:我遺漏的
*b
和*c
定義之間是否存在任何隱藏的差異?
這兩個指針上的指針運算將保持不變。 因為數組內部衰減為指向其中第一個元素的指針,即arr[n]
將被轉換為“指向arr
的指針”類型的表達式,其值將是數組中第一個元素的地址。
Q2:指針算術是否只取決於指針的大小?
不,這取決於所指向的基礎類型的大小。 即使在您提供的示例輸入中, ++a
和++b
也會產生不同的結果。 因為++a
通過sizeof(int)
偏移指針,即 4。但是在++b
的情況下,您的指針會增加5 * sizeof(int)
的大小 20(十進制)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.