![](/img/trans.png)
[英]Pointer to struct with pointer to array of pointers to structs. Dynamic memory in C
[英]Array of pointers to structs in a pointer to a struct
下面的代碼嘗試初始化節點,並在此過程中動態初始化指向子節點的指針數組。 但是,我遇到了Segmentation fault: 11
當我嘗試訪問子級時。 我意識到我不應該獲取任何有意義的值(即,它將只是內存中的垃圾),但是我不知道為什么會遇到分段錯誤。
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#define INIT_SIZE 10
typedef struct node_t node_t;
struct node_t {
char *word;
node_t **children;
int arr_len;
};
void set_array_vals(node_t *root);
int main(int argc, char const *argv[]) {
char *word = "hello";
node_t *root = malloc(sizeof(node_t));
assert(root);
root->children = malloc(sizeof(node_t *) * INIT_SIZE);
assert(root->children);
root->arr_len = INIT_SIZE;
root->word = malloc((sizeof(char)) * (strlen(word) + 1));
assert(root->word);
strcpy(root->word, word);
set_array_vals(root);
printf("Arr len: %d\n", root->arr_len);
return 0;
}
void set_array_vals(node_t *root) {
int i;
for (i=1; i<root->arr_len; i++) {
node_t *this_node = root->children[i];
printf("%d: %d\n", i, this_node->arr_len);
}
}
在set_array_vals
您從“ array” root->children
獲取指針,但是該數組未初始化,並且指針將是不確定的並且看似隨機的。 取消引用那些指針會導致未定義的行為 。
同樣,您似乎忘記了數組索引從零開始 。 並且一旦使root->children
數組中的所有指針有效,就必須記住還要初始化它們指向的結構,否則this_node->arr_len
的值將是不確定的。
正如其他人指出的那樣,首先, children
是node_t **
類型的,並且您僅為root->children
分配了內存,而不為root->children[row]
分配了內存。 為root->children[row]
動態分配內存並分配一些值。 看起來像
root->arr_len = INIT_SIZE;
for(int row = 0; row < root->arr_len ;row++) {
root->children[row] = malloc(sizeof(node_t));/* allocate memory for each children */
root->children[row]->arr_len = row + 99;/* ?? assign some values into member of struct so that you can print in
set_array_vals & verify */
}
在set_array_vals()
從i=0
開始打印,如上所述,您set_array_vals()
內存從root->children[0]
分配給root->children[9]
,超出大小的訪問可能導致不確定的行為。
void set_array_vals(node_t *root) {
for (int i = 0; i < root->arr_len; i++) { /* start printing from i=0 , not i=1 */
#if 0
node_t *this_node = root->children[i]; /* no need of any temporary pointer */
printf("%d: %d\n", i, this_node->arr_len);
#endif
printf("%d: %d\n", i, root->children[i]->arr_len);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.