指针之间的区别的指针和指针数组? [英] Difference between pointer to pointer and pointer to array?
问题描述
由于数组的名称实际上是一个指向数组的指针,以下code中的第一个元素:
Given that the name of an array is actually a pointer to the first element of an array, the following code:
#include <stdio.h>
int main(void)
{
int a[3] = {0, 1, 2};
int *p;
p = a;
printf("%d\n", p[1]);
return 0;
}
打印 1
,符合市场预期。
现在,因为我可以创建一个指向指针的指针,我写了以下内容:
Now, given that I can create a pointer that points to a pointer, I wrote the following:
#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
但是,相反,它出错在编译的时候,他说:
But instead, it goes wrong at compile time, saying:
test.c: In function ‘main’:
test.c:11:5: warning: assignment from incompatible pointer type [enabled by default]
这是为什么分配错了吗?如果 P1
是一个指向一个指向 INT
和 A
是一个指向 INT
(因为它是一个数组 INT
S的名字),为什么不能' T I分配&放大器;一个
到 P1
Why is that assignment wrong? If p1
is a pointer to a pointer to an int
and a
is a pointer to an int
(because it's the name of an array of int
s), why can't I assign &a
to p1
?
推荐答案
11号线
p1 = &a;
其中, P1
的类型为 INT **
和 A
已键入 INT [3]
,对吧?
where p1
has type int **
and a
has type int[3]
, right?
好; &放大器;一个
已键入 INT(*)[3]
以及该类型是不兼容 INT **
因为编译器告诉你。
Well; &a
has type int(*)[3]
and that type is not compatible with int**
as the compiler told you
您可能想尝试
p1 = &p0;
和阅读的C-FAQ ,特别是第6。
在短:数组不是指针和指针不是数组
这篇关于指针之间的区别的指针和指针数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!