我认为我非常了解引用和指针。以下是我(认为我)知道的:
int i = 5; //i is a primitive type, the value is 5, i do not know the address.
int *ptr; //a pointer to an int. i have no way if knowing the value yet.
ptr = &i; //now i have an address for the value of i (called ptr)
*ptr = 10; //Go to the value in ptr, use it to find a location and store 10 there
请随时评论或更正这些陈述。
现在我正在尝试跳转到指针数组。以下是我不知道的:
char **char_ptrs = new char *[50];
Node **node_ptrs = new Node *[50];
我的理解是我有 2 个指针数组,一组指向字符的指针和一组指向节点的指针。因此,如果我想设置这些值,我会这样做:
char_ptrs[0] = new char[20];
node_ptrs[0] = new Node;
现在我有一个指针,在我的数组的 0 位置,在每个相应的数组中。同样,如果我感到困惑,请随时在此处发表评论。
那么,** 运算符是做什么的?同样,将单个 * 放在实例化旁边做什么 (*[50])? (具体叫什么,实例化?)
最佳答案
一些评论:
*ptr = 10; // Doesn't need to "go get" the value. Just overwrites it.
还有:
char **char_ptrs = new char *[50];
Node **node_ptrs = new Node *[50];
更容易认为你有两个数组。但是,从技术上讲(就编译器而言),您拥有的是两个 指针。一个是指向a的指针(pointer to a char),另一个是指向a的指针(pointer to a node)。
这很容易从变量的声明中看出,顺便说一句,从右到左最容易阅读:
char **char_ptrs
Reading right to left:
char_ptrs
is a pointer to a pointer tochar
在指针旁边放一个 * 被恰本地称为取消引用该指针。由于数组在技术上并不存在,因此数组上的运算符 [] 也是一种解引用操作:arr[i]
是 *(arr + i)
的另一种写法。要正确理解这一点,您需要熟悉 pointer arithmetic .
多个连续的 *s:每个 *s 都会取消引用它所操作的表达式的结果。所以写的时候:
char c = **char_ptrs;
会发生什么:
char_ptrs
is a pointer to a pointer to a char. Dereferencing it once (for the rightmost *) gets you its value, which is a pointer to a char. Dereferencing that value (for the leftmost *) gives you its own value in turn, which is a char. In the end,c
contains the value of the char stored in memory at the place where the pointer pointed to by char_ptrs (in other words, the first pointer in your array) points.
相反,如果您编写 **char_ptrs = 'a';
那么您正在更改该内存位置中的值。
关于c++ - 理解 C++ 指针(当它们指向指针时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2814512/