代码导致数据结构操作崩溃

Code crashes data structure manipulation

本文关键字:操作 崩溃 数据结构 代码      更新时间:2023-10-16

在下面的代码中,对于每个节点都包含一个指向所有子节点(类型为节点)的指针的指针

在崩溃的行中,我正在为child_array分配内存,并返回一个类型为 node * 的指针。

现在在我的实际节点中,我将 ptr 到 ptr child_array的值设置为

有人可以解释为什么这会崩溃。在数学上,方程的两边都是(节点*)。

我可以猜到的一件事是,当我取消引用child_array一次以分配节点*时,取消围栏的值可能指向垃圾,而没有初始化。在这种情况下,我如何以及何时安全地初始化它?

#include "stdafx.h"
#include <iostream>
using namespace std;
struct node
{
    int val;
    int num_child;
    node** child_array;
};
node *head = NULL;
node* addelement(int parent_id)
{
    cout << " You are the child of " << parent_id << endl;
    int val, child_count;
    cout << "Enter value of element" << endl;
    cin >> val;
    cout << "Enter no of children" << endl;
    cin >> child_count;
    node* new_node = new node;
    if(new_node)
    {
        new_node->num_child = child_count;
        new_node->val = val;
        node *child_head = (node *)new node[child_count];

下面捣碎的 lINE

        *(new_node->child_array) = child_head; 
    }
    else
    {
        //assert(false);
    }
    for( int i=0; i<child_count; i++)
    {
        new_node->child_array[i] = addelement(val);
    }
    return new_node;
}
void printTree(node *head)
{
    if(head!=NULL)
    {
        cout << head->val << endl;
        for( int i=0; i<head->num_child;i++)
        {
            printTree(head->child_array[i]);
        }
    }
}
int _tmain(int argc, _TCHAR* argv[])
{
    head = addelement(0);
    printTree(head);
    cout << endl;
    cout << " Tree Elementsn";
    printTree(head);
    return 0;
}

取消引用未初始化的指针并写入未分配的内存:

*(new_node->child_array) = ...

还有一个概念问题。您是要创建node数组还是node*数组?