指向类树类中指针数组的指针

时间:2015-05-07 18:14:07

标签: c++ arrays pointers

我的C / C ++指针存在一个主要问题。我试图用节点实现树状结构。每个节点都有一个指向另一个指向其他节点的指针数组的指针。

这是我的Node结构:

struct Node
{
    int key_value;
    bool is_init = false;
    Node* children;
};

我的问题似乎出现在这些行的某个地方

bool flag = false;
Node *temp = &(root->children[mod]);
while (!flag)
{
    mod = key % k;
    if (temp->children[mod].is_init != false)
    {
        if (temp->children[mod].key_value != key)
        {
            temp = &(temp->children[mod]);
            continue;
        }
        else
        {
            printf("%d exsist\n", key);
            return;
        }
    }
    else
    {
        temp->children = new Node[k];
        temp->children[mod].is_init = true;
        temp->children[mod].key_value = key;
        flag = true;
    }
}

通过阅读错误消息我认为是因为根级以下的孩子不指向其他节点阵列。

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:0)

代码不完整,无法找到错误。您可能希望将结构修改为类似的结构,以便跟踪分配的结构数量:

 struct Node 
   {
       int key_value;
       bool is_init = false;
       Node* children;
       int len;
   };

并在此处添加支票:

if (temp->len > mod && temp->children[mod].is_init != false)
{ ...
}

答案 1 :(得分:0)

我认为你创建新节点的方式是错误的。只有在找不到temp->children[mod].is_init != false时才会创建新的节点数组,但是当它为空时,则不会创建新的节点数组。在现有条件出现之前,可能需要进行NULL检查。

OR

 temp = &(temp->children[mod]);

在将子项分配给temp

之前检查子项是否存在

答案 2 :(得分:0)

开始......
更改:

struct Node
{
    int key_value;
    bool is_init = false;//illegal initialization in C
    Node* children;
};

收件人:

struct Node
{
    int key_value;
    bool is_init;
    Node* children;
};  
typedef struct Node NODE;  

然后你可以像这样创建和初始化:

int main(void)
{
    NODE *head = {0}, *first = {0}, *temp = {0};
    head = malloc(sizeof(NODE));
    head->key_value = 10;
    head->is_init = 0;
    if(first != 0)
    {
        temp->children = head;
        temp = head;
    }
    else
    {
        first = temp = head; //save location of first item
    }
    // etc., etc.
    // ...