鑑於數組的名稱實際上是一個指針數組,下面的代碼的第一個元素:指向指針的指針和指向數組的指針之間的區別?
#include <stdio.h>
int main(void)
{
int a[3] = {0, 1, 2};
int *p;
p = a;
printf("%d\n", p[1]);
return 0;
}
打印1
,如所預期。
。現在,因爲我可以創建一個指向指針的指針,我寫了下面:
#include <stdio.h>
int main(void)
{
int *p0;
int **p1;
int (*p2)[3];
int a[3] = {0, 1, 2};
p0 = a;
p1 = &a;
p2 = &a;
printf("p0[1] = %d\n(*p1)[1] = %d\n(*p2)[1] = %d\n",
p0[1], (*p1)[1], (*p2)[1]);
return 0;
}
我預期編印
p0[1] = 1
(*p1)[1] = 1
(*p2)[1] = 1
但是,相反,它會在編譯時出錯,說:
test.c: In function ‘main’:
test.c:11:5: warning: assignment from incompatible pointer type [enabled by default]
爲什麼這個分配是錯誤的?如果p1
是指向指向int
的指針,並且a
是指向int
(因爲它是int
s的數組的名稱),爲什麼我不能將&a
指定爲p1
?
某個時間以前,我寫了[對類似問題的回答](http://stackoverflow.com/questions/5181237/confusion-in-data-types-in-a-2d-array),你可能會喜歡。 – pmg
謝謝你的提示! – jpmelos