首页 文章

使用指针C创建动态分配的数组

提问于
浏览
1

所以我目前有一个简单的struct(linkedlist),我将在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;
    }
}

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

2 回答

  • 2

    有两种方法 . 您可以分配一个结构数组并引入另一个指针,该指针将指向数组中将扮演头部角色的元素 .

    例如

    Node *head = nodes;
    

    (在这种情况下,head指向节点[0])

    在不需要列表之后,您必须使用operator删除它

    delete [] nodes;
    

    或者您确实可以像这样为结构分配一个指针数组

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

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

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

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

    然后删除数组本身

    delete [] nodes;
    

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

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

    我建议你这个结构:

    class myList {
    
    struct Node {
    string value;
    Node* next;
    }
    
    /*Public methods .. Add/Set/Get/Next/isEmpty.. etc ... */
    Node* head, *tail;
    };
    

    在主要: myList* lis = new myList[number]; 然后你有多少名单!并且通过方法和运算符在类中完成所有工作,就像你想要下一个节点只是调用 lis[0].getNext(); 如果你想跳过当前节点那么 lis[0].Next(); ...等等 .

    这个如何工作,你尝试做的就像C程序!

相关问题