Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 代码崩溃数据结构操纵_C++_Memory Management_Data Structures - Fatal编程技术网

C++ 代码崩溃数据结构操纵

C++ 代码崩溃数据结构操纵,c++,memory-management,data-structures,C++,Memory Management,Data Structures,在下面的代码中,for every节点包含一个指向所有子节点(类型为Node)指针的指针 在崩溃的行中,我将内存分配给child_数组,该数组返回node*类型的指针 现在在我的实际节点中,我将子数组ptr的值设置为 有人能解释一下为什么会这样吗。从数学上讲,方程的两边都是(节点*) 我能猜到的一件事是,当我取消引用child_数组一次以分配一个节点*时,取消引用的值可能会指向正在初始化oput的垃圾。在这种情况下,我如何&何时安全地初始化它 #include "stdafx.h" #inclu

在下面的代码中,for every节点包含一个指向所有子节点(类型为Node)指针的指针

在崩溃的行中,我将内存分配给child_数组,该数组返回node*类型的指针

现在在我的实际节点中,我将子数组ptr的值设置为

有人能解释一下为什么会这样吗。从数学上讲,方程的两边都是(节点*)

我能猜到的一件事是,当我取消引用child_数组一次以分配一个节点*时,取消引用的值可能会指向正在初始化oput的垃圾。在这种情况下,我如何&何时安全地初始化它

#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];
#包括“stdafx.h”
#包括
使用名称空间std;
结构节点
{
int-val;
int num_child;
节点**子数组;
};
node*head=NULL;
节点*加法元素(整数父元素\u id)
{
cout child_数组)=child_头;
}
其他的
{
//断言(假);
}
for(int i=0;ichild_数组[i]=addelement(val);
}
返回新的_节点;
}
无效打印树(节点*头)
{
if(head!=NULL)
{
cout val child_数组[i]);
}
}
}
int _tmain(int argc,_TCHAR*argv[]
{
头=加法(0);
打印树(头);

您是否可以取消对未初始化指针的引用并写入未分配的内存:

*(new_node->child_array) = ...

还有一个概念上的问题。你是想创建一个
节点数组
,还是一个
节点数组*

除非你给child\u数组赋值,否则它就是垃圾。我想创建一个节点数组*。但我想我可以使用节点数组。如果你想创建一个
节点数组*
,那么
新建否de[儿童计数]
不正确。
*(new_node->child_array) = ...