以下の次のコードでは、すべてのノードに、(ノードタイプの)すべての子ノードのポインターへのポインターが含まれています。
クラッシュする行では、child_arrayにメモリを割り当てており、ノード*型のポインタを返します。
これで、実際のノードで、child_arrayptr-to-ptrの値を次のように設定しています。
誰かがこれがクラッシュしている理由を説明できますか?数学的には、方程式の両辺は(ノード*)です。
私が推測できることの1つは、child_arrayを1回逆参照してノード*を割り当てると、逆参照された値が初期化されているガベージウィズアウトを指している可能性があることです。その場合、いつどのように安全に初期化できますか?
#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;
}