【问题标题】:C++: Segmentation fault when inserting pointer into a struct's double pointer arrayC ++:将指针插入结构的双指针数组时出现分段错误
【发布时间】:2021-02-27 10:39:40
【问题描述】:

我有一个具有以下定义的 TreeNode 类,其中包含一个指向 TreeNode 指针数组的双指针:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

typedef struct TreeNode { 
   int key;
   int val;
   bool flag;
   int num_children;
   TreeNode **children;
} TreeNode; 

在以下代码中:

TreeNode* node1 = new TreeNode{1, 1, true, 0, NULL};
TreeNode* node2 = new TreeNode{2, 2, true, 0, NULL};
TreeNode* node3 = new TreeNode{3, 2, true, 0, NULL};
TreeNode* node4 = new TreeNode{4, 2, true, 0, NULL};
TreeNode* node5 = new TreeNode{5, 2, true, 0, NULL};

// Assign node2 to be the child of node1
node1->children = &node2;
cout << "Assigned node1->children = &node2;" << endl;

// Assign node3 to be the second child of node1
node1->children[1] = node3;
cout << "Assigned node1->children[1] = node3;" << endl;
node1->children[2] = node4;
cout << "Assigned node1->children[2] = node4;" << endl;
node1->children[3] = node5;
cout << "Assigned node1->children[3] = node3;" << endl;

以下代码行出现分段错误:

node1->children[2] = node4;

考虑到我使用 new 关键字动态分配内存,这似乎很奇怪。此外,我无法为数组分配固定数量的内存,因为子数组可以在程序中随时更改大小。

【问题讨论】:

  • 你是 children of array can change size at any moment,听起来你需要像 vector 这样的动态数组,而不是静态数组。可能是std::vector&lt;std::vector&lt;TreeNode&gt; &gt; children

标签: c++ memory memory-management


【解决方案1】:
node1->children = &node2;

所以,node1-&gt;children 包含node2 的地址。

node1->children[2] = node4;

这没有意义。由于node1-&gt;children 包含指向node2 的指针而不是数组,因此node1-&gt;children[2] 不存在——没有为其分配空间,因此无法设置其值。

你想要一个指针数组,但你没有在任何地方创建任何空间来存储指针数组。

您的代码在概念上与此没有什么不同:

int a;
int *b = &a;
b[1] = 7;

虽然b[0] 指向a,但b[1] 无效,因此无法赋值。如果我们想要一个指向int 的指针数组,我们需要在某个地方为一个指针腾出空间。某处必须有new int*[2]

您可能想要执行类似node1-&gt;children = new TreeNode*[5]; 的操作来分配一个包含5 个指向TreeNodes 的指针的数组。然后,您可以将node-&gt;children[0]node-&gt;children[4] 设置为指向您想要存储指针数组的位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-23
    • 2018-07-12
    • 1970-01-01
    相关资源
    最近更新 更多