【问题标题】:Code crashes data structure manipulation代码崩溃数据结构操作
【发布时间】:2012-10-08 00:24:55
【问题描述】:

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

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

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

有人可以解释为什么会崩溃。从数学上讲,等式的两边都是(节点*)。

我可以猜到的一件事是,当我取消引用 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];

下划线

        *(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 Elements\n";
    printTree(head);
    return 0;
}

【问题讨论】:

  • 除非你给 child_array 赋值,否则它就是垃圾。

标签: c++ memory-management data-structures


【解决方案1】:

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

*(new_node->child_array) = ...

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

【讨论】:

  • 我正在尝试创建一个节点数组*。但我想我可以只使用节点数组。
  • 如果你试图创建一个node*的数组,那么new node[child_count]是不正确的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-03
  • 2019-06-13
  • 1970-01-01
  • 1970-01-01
  • 2011-02-28
  • 1970-01-01
  • 2022-10-06
相关资源
最近更新 更多