为什么一个指针的指针数组不兼容的指针? [英] Why is a pointer to a pointer incompatible with a pointer to an array?
问题描述
好吧,我无法理解指针的指针VS指向数组的指针。
请看下面的code:
OK, I'm having trouble understanding pointers to pointers vs pointers to arrays. Consider the following code:
char s[] = "Hello, World";
char (*p1)[] = &s;
char **p2 = &s;
printf("%c\n", **p1); /* Works */
printf("%c\n", **p2); /* Segmentation fault */
为什么第一个printf的工作,而第二个不?
Why does the first printf work, while the second one doesn't?
据我了解,S是一个指向数组的第一个元素(即H)。
因此宣告P2为char **意味着它是一个指针指向一个字符。使得它指向的应该是合法的,因为S是一个指向一个char。因而取消引用它(即** P2)应该给H。但事实并非如此!
From what I understand, 's' is a pointer to the first element of the array (that is, 'H'). So declaring p2 as char** means that it is a pointer to a pointer to a char. Making it point to 's' should be legal, since 's' is a pointer to a char. And thus dereferencing it (i.e. **p2) should give 'H'. But it doesn't!
推荐答案
您误会出在什么取值
是。它的不的指针:它是一个数组
Your misunderstand lies in what s
is. It is not a pointer: it is an array.
现在在大多数情况下,取值
计算为一个指向数组的第一个元素:相当于&放大器; S [0]
,一个指向'H'
。虽然这里最重要的事情是,你得到的指针值评估时,取值
是一个临时的,短暂的价值 - 就像&放大器; S [0]
。
Now in most contexts, s
evaluates to a pointer to the first element of the array: equivalent to &s[0]
, a pointer to that 'H'
. The important thing here though is that that pointer value you get when evaluating s
is a temporary, ephemeral value - just like &s[0]
.
由于该指针是不是一个永久性的对象(它实际上不是什么存储在取值
),你不能在这做一个指针到指针点。使用指针到指针,你必须有一个指针对象指向 - 例如,下面是确定:
Because that pointer isn't a permanent object (it's not actually what's stored in s
), you can't make a pointer-to-pointer point at it. To use a pointer-to-pointer, you must have a real pointer object to point to - for example, the following is OK:
char *p = s;
char **p2 = &p;
如果您评估 * P2
,你告诉编译器来加载东西 P2
点和把它当作一个指针到字符。这很好,当 P2
在没有实际指向一个指针到字符;但是当你做的char ** P2 =安培; S;
的东西 P2
点是不是一个指针在所有 - 它是一个数组(在这种情况下,它是13 字符
s的块)。
If you evaluate *p2
, you're telling the compiler to load the thing that p2
points to and treat it as a pointer-to-char. That's fine when p2
does actually point at a pointer-to-char; but when you do char **p2 = &s;
, the thing that p2
points to isn't a pointer at all - it's an array (in this case, it's a block of 13 char
s).
这篇关于为什么一个指针的指针数组不兼容的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!