无法为结构变量动态设置数组大小

Unable to dynamically set array size for struct variables

下面的两部分代码都大大简化了我的实际代码的独立版本。这些例子足以说明问题。下面的第一部分代码工作正常。 section section 试图开始使它成为class的一部分。挑战在于使 maxSize 变量可以由用户在运行时在构造函数中设置,而不是硬编码值。除此之外,我正在寻找一种解决方案,它允许我只需要更改结构的声明方式并更改 Initialize() 方法(最终将成为 class 构造函数)中所做的事情。我已经浪费了几个小时进行更改,这些更改需要更改其他 50 多种方法,但从未成功过,所以我想知道是否有我错过的解决方案不需要更改其他 50 多种方法。

工作代码:

#include <cstdio>
#include <cstdlib>
#include <iostream>

using std::cout;
using std::endl;

const int maxSize = 3;
Node *root;

struct Item{
    string key;
    string value;
};

struct Node{
    int count;

    Item key[maxSize + 1];
    Node *branch[maxSize + 1];
};

/* 
-------
   ^
   |
50+ of other methods, all using these structs as pointers, 
pointers to pointers, & references.
   |
   v
-------
*/

int main(int argc, char *argv[])
{

    return 0;
}

仅举一个例子,尝试逐步修改整个代码,使其成为 class:

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;

int maxSize;
Node *root;

struct Item{
    string key;
    string value;
};

struct Node{
    int count;
    Item *item;
    Node *branch;

    // doesn't work because it requires 
    // modification of the rest of the code
    // which has only resulted in an infinite loop of debugging
    void init(int size)
    {       
        item = new Item[size]; 
        branch = new Node[size]; 
    }
};

void Initialize(int size)
{
    maxSize = size;
}

/* 
-------
   ^
   |
50+ other methods, all using these structs as pointers, 
pointers to pointers, & references.
   |
   v
-------
*/


int main(int argc, char *argv[])
{
    Initialize(5);

    return 0;
}

在您的第一个示例中,Node *branch[maxSize + 1]; 是一个节点指针数组。在您的第二个示例中,branch = new Node[size]; 创建了一个节点数组 objects。这是一个显着的差异,可能是让您失望的原因。

你想要的可以用原始语法完成:

Node **branch;
branch = new Node*[size];

但正如有人已经指出的那样,std::vector 通常更容易也更好:

std::vector<Node*> branch;
branch.resize(size);