C ++ struct - 指向指针和动态数组的指针

时间:2022-09-01 11:27:39

I want to implement a tree trie and insert an example value into the key variable I am using a pointer to pointer and creating a dynamic array of 100 elements but my application crashes after starting.

我想实现一个树trie并将一个示例值插入到键变量中我使用指针指针并创建一个包含100个元素的动态数组但是我的应用程序在启动后崩溃了。

#include<iostream>
using namespace std; 

struct node {
  int key;
  node **children;          
};

int main() {
  node *child;          
  child = new node;
  child->children = new node *[100];
  child->children[20]->key = 90;        
  cout<<child->children[20]->key;

  return 0;
}

1 个解决方案

#1


You need to allocate memory for child->children[20]. You allocated memory for child->children but not for the elements in the array. You can do this as follows:

你需要为child-> children [20]分配内存。您为child-> children分配了内存,但没有为数组中的元素分配内存。你可以这样做:

for (int i=0;i<100;++i) {
  child->children[i] = new node;
}

By storing a node * you are storing the address of a node which contains the address of an array of addresses of nodes. This means that you need to allocated memory for all three levels of the hierarchy. You only allocated memory for two of the layers.

通过存储节点*,您将存储包含节点地址数组地址的节点的地址。这意味着您需要为层次结构的所有三个级别分配内存。您只为其中两个图层分配了内存。

#1


You need to allocate memory for child->children[20]. You allocated memory for child->children but not for the elements in the array. You can do this as follows:

你需要为child-> children [20]分配内存。您为child-> children分配了内存,但没有为数组中的元素分配内存。你可以这样做:

for (int i=0;i<100;++i) {
  child->children[i] = new node;
}

By storing a node * you are storing the address of a node which contains the address of an array of addresses of nodes. This means that you need to allocated memory for all three levels of the hierarchy. You only allocated memory for two of the layers.

通过存储节点*,您将存储包含节点地址数组地址的节点的地址。这意味着您需要为层次结构的所有三个级别分配内存。您只为其中两个图层分配了内存。