c++ - 理解 C++ 指针(当它们指向指针时)

标签 c++ memory pointers

我认为我非常了解引用和指针。以下是我(认为我)知道的:

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 to char

在指针旁边放一个 * 被恰本地称为取消引用该指针。由于数组在技术上并不存在,因此数组上的运算符 [] 也是一种解引用操作: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/

相关文章:

C malloc 指向 NULL 的指针不起作用

c++ - 指针数组成员,是否初始化?

c++ - 将对象指针复制到动态对象数组中

c++ - 搜索不同于 "X"的第一个字符的字符串

c++ - 在 Windows 7 下编译的 Dll 在 Windows XP 下不起作用

c - 如何为 C 结构体中的 char 指针分配内存?

c - 2d-array- arr[][0] 是什么意思?

c++ - 用于 C++ 开发的 Refactor Pro 与 Visual Assist X

c++ - 在 C++ 中访问 C 结构

java - Java 的 new 关键字是否一定表示堆分配?