Selhar - 4 months ago 13

C Question

I have the following structure:

`typedef struct TRIE_NODE`

{

char* word;

struct TRIE_NODE* node[26];

}TRIE_NODE;

I create a node called head,

`TRIE_NODE *head = NULL;`

`void initialize_node(TRIE_NODE *current_node)`

{

int MAX = 25;

current_node = malloc(sizeof(TRIE_NODE));

for(int i = 0; i < MAX; i++)

{

current_node->node[i] = NULL;

if(current_node->node[i] == NULL)

printf("\n -- \n");

}

}

However, i get a segmentation fault whenever i try to even read

`current_node->node[i]`

`current_node->node`

`TRIE_NODE`

Answer

You do everything correctly, except this line

```
current_node = malloc(sizeof(TRIE_NODE));
```

which modifies the local copy of `current_node`

. The pointer in the caller remains unchanged.

To fix this problem, pass a pointer to pointer, and assign with an indirection operator:

```
void initialize_node(TRIE_NODE **current_node_ptr) {
...
*current_node_ptr = malloc(sizeof(TRIE_NODE));
...
}
```