c++ - 使用指向结构 C++ 的指针创建动态分配的数组

标签 c++ arrays pointers struct

所以我目前有一个简单的结构(链表),我将在 HashMap 中使用它:

struct Node {
    std::string key, value;
    Node* head;
}

我目前正在尝试动态分配一个数组,其中包含指向每个结构的指针。这就是我现在拥有的...

Node* nodes = new Node[100]

我知道这会将一个包含 100 个节点的数组分配到内存中(稍后我将不得不删除它);然而,在尝试遍历这些节点时(我将其实现为链表)...

for (int x = 0; x < 100; x++) {
    Node current = nodes[x]; // Problem is I wanted an array to node pointers. This is not a pointer.
    while (current != nullptr) { // this isn't even legal since current is not a pointer.
        // DO STUFF HERE
        current = current.next; // This is not a pointer access to a method. I'm looking to access next with current->next;
    }
}

希望我已经足够清楚了。有人可以如何分配指向结构的动态指针数组吗?到目前为止,我能够动态分配一个结构数组,而不是一个指向结构的指针数组。

最佳答案

有两种方法。要么分配一个结构数组,再引入一个指针,该指针将指向数组中将扮演头部角色的元素。

例如

Node *head = nodes;

(在本例中 head 指向节点[0])

在不需要列表后,您必须使用运算符将​​其删除

delete [] nodes;

或者你确实可以像这样分配一个指向结构的指针数组

Node **nodes = new Node *[100];

但在这种情况下,数组的每个元素依次应该是指向动态分配对象的指针;

要删除列表,您首先必须删除数组元素指向的每个对象,例如在循环中

for ( int i = 0; i < 100; i++ ) delete nodes[i];

然后删除数组本身

delete [] nodes;

例如,在分配数组时用零初始化数组的每个元素是个好主意

Node **nodes = new Node *[100]();

关于c++ - 使用指向结构 C++ 的指针创建动态分配的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33815095/

相关文章:

c++ - C++中的宏处理器

C++ OpenCV : Convert vector<vector<Point>> to vector<vector<Point2f>>

javascript - JavaScript 是否在内部将数组转换为对象?

c - hashedmap 和指向结构体的指针 : CXX0030: Error: expression cannot be evaluated

c++ - 基于范围用于原始类型

android - 使用 jni 包装 C++ 库

php - 为什么这个 PHP 代码只回显 "Array"?

java - 嵌套循环在 Mastermind 游戏中无法正常工作

c - 需要 C 程序帮助

c++ - 如何将 shared_ptr 与指向不应释放的结构的指针一起使用