[英]Pointers to arrays
我找到了一個指向數組的指針的例子,這對我來說沒有多大意義,我想知道是否有人可以幫助我?
int a[5] = 0,1,4,89,6;
int *p = a; 'p points at the start of a'
p[3] = 1; 'a[3] is now 6'
我不確定第三行p [3] = 1的工作方式以及如何導致a [3] =6。感謝您的提前幫助。
這有點不正確。 a[3]
是1
,不是6
。
以下是逐行說明:
int a[5] = 0,1,4,89,6;
int *p = a; //'p points at the start of a'
p[3] = 1; //'a[3] is now 1 not 6'
第一行初始化數組。 我認為數字應該有{},但是如果與您一起編譯就可以了。 我認為這應該是這樣的:
int a[5] = {0,1,4,89,6};
第二行創建指向int p
指針,並將其初始化為a
的地址。 數組和指針在C中緊密相關,因此,現在,您有2個變量a
和p
指向一個相同的內存地址。
第三行-將p[3]
設置為1
,這一次您將p
作為int數組訪問(由於數組和指針之間的這種關系,所以可能出現)。 因為p
和a
點在相同的內存地址中,所以這意味着a[3]
現在為1
另外,備注不正確,必須為/ * * /或//。
更新 :
大衛的評論非常重要。
數組是順序保留的內存,能夠存儲幾個數組值(在您的情況下為5 int)。
指針是一個指針,可以指向可以指向int變量的任何地方:
int a = 5;
int *b = &a;
也可以像您一樣指向數組。 在這兩種情況下,您都可以使用[],但是如果它指向單個值,則任何大於零的數組下標都是錯誤的,例如
int a = 5;
int *b = &a;
*b = 4; // OK.
b[0] = 4; // OK.
b[1] = 4; // compiles correctly, but is **wrong**.
// it will overwrite something in memory
// and if program not crash,
// it will be security hole.
int x[10];
int *y = x;
*y = 4; // works correctly for y[0],
// but makes it difficult to read.
y[0] = 5; // OK
y[9] = 5; // OK
y[10] = 5; // compiles correctly, but is **wrong**.
// it is after last element of x.
// this is called **buffer overflow**.
// it will overwrite something in memory
// and if program not crash,
// it will be security hole.
更新 :
我建議您檢查這篇文章
http://boredzo.org/pointers/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.