【发布时间】:2011-09-22 09:05:38
【问题描述】:
鉴于数组名实际上是指向数组第一个元素的指针,下面的代码:
#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 的指针(因为它是ints 的数组的名称),为什么我不能分配@987654332 @到p1?
【问题讨论】:
-
前段时间我写了an answer to a similar question你可能会喜欢。
标签: c arrays pointers declaration dereference