解引用一个指针数组? [英] Dereferencing a pointer to an array?
问题描述
参照该注释行:
- 在该示例工作为什么加括号打印阵列中的所有内容?
这个例子打印一,然后打印垃圾。
的#include<&iostream的GT;诠释主(){
为const char * a [3] = {一,二,三化};
常量字符*(* p)的[3] =&放大器;一个;
的for(int i = 0;我3;;我++){
性病::法院LT&;< * P [1] - ;&下;的std :: ENDL; //这一行
}
返回0;
}
它的工作原理更改为此后:
的std ::法院LT&;< (* p)的[1] - ;&下;的std :: ENDL;
P
是一个指向3个元素的一个这样的数组:
┌─────┬─────┬─────┐
││││
└─────┴─────┴─────┘
^
└─p
请注意它指向整个阵列,而不是一个单一的元素。
这位前pression * P [I]
被视为 *(P [I])
由于操作者$ p $ pcedence(相当于 *(*(p + I))
)。这意味着你将索引指向数组。如果你这样做 P [1]
,比如你一起下一个阵列,并试图取消对它的引用移动指针:
┌─────┬─────┬─────┐
││││
└─────┴─────┴─────┘
^
└─P + 1个
我们可以看到,里面空空如也,你会得到未定义的行为。但是,当你做(* P)[我]
(等同于 *((* P)+ I)
),你正在确定取消引用首先发生。反引用给我们的阵列本身,然后可以通过阵列到指针转换隐式转换成一个指向数组第一个元素。所以,你得到的是:
┌─────┬─────┬─────┐
││││
└─────┴─────┴─────┘
^
└─* P
在这种情况下,指针是在阵列指向的元素的,而不是整个阵列。如果随后指数,例如,(* P)[1]
,你会得到:
┌─────┬─────┬─────┐
││││
└─────┴─────┴─────┘
^
└─(* P)+ 1个
这为您提供了一个有效的为const char *
然后可以通过 COUT
输出。
Referring to the line with the comment:
- Why does adding parenthesis in the example work to print all the contents of the array?
The example prints "one", then prints garbage.
#include <iostream>
int main() {
const char* a[3] = { "one", "two", "three" };
const char*(*p)[3] = &a;
for(int i = 0; i < 3; i++) {
std::cout << *p[i] << std::endl; // this line
}
return 0;
}
It works after changing to this:
std::cout << (*p)[i] << std::endl;
p
is a pointer to an array of 3 elements like this:
┌─────┬─────┬─────┐
│ │ │ │
└─────┴─────┴─────┘
^
└─ p
Note that it points at the whole array, not a single element of it.
The expression *p[i]
is treated as *(p[i])
due to operator precedence (which is equivalent to *(*(p + i))
). This means that you are indexing the pointer to the array. If you do p[1]
, for example, you move the pointer along to the "next" array and attempt to dereference it:
┌─────┬─────┬─────┐
│ │ │ │
└─────┴─────┴─────┘
^
└─ p + 1
As we can see, there is nothing there, and you'll get undefined behaviour. However, when you do (*p)[i]
(equivalent to *((*p) + i)
), you are making sure the dereference happens first. The dereference gives us the array itself, which can then be implicitly converted by array-to-pointer conversion to a pointer to the arrays first element. So what you get is:
┌─────┬─────┬─────┐
│ │ │ │
└─────┴─────┴─────┘
^
└─ *p
In this case, the pointer is pointing at the array element and not the whole array. If you then index, for example, (*p)[1]
, you'll get:
┌─────┬─────┬─────┐
│ │ │ │
└─────┴─────┴─────┘
^
└─ (*p) + 1
This gives you a valid const char*
which can then be outputted by cout
.
这篇关于解引用一个指针数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!