[英]C++: ways to free a dynamic array (member of a struct) and a pointer to this struct
[英]C++ struct - pointer to pointer and dynamic array
我想實現一個樹特里並將一個示例值插入到鍵變量中,我正在使用一個指向指針的指針並創建一個包含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;
}
您需要為child->children[20]
分配內存。 您為child->children
分配了內存,但沒有為數組中的元素分配內存。 您可以按照以下步驟進行操作:
for (int i=0;i<100;++i) {
child->children[i] = new node;
}
通過存儲node *
您正在存儲的地址node
包含的地址的數組的地址nodes
。 這意味着您需要為層次結構的所有三個級別分配內存。 您僅為兩個層分配了內存。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.