Selhar Selhar - 2 months ago 7
C Question

Initialization of a structure that contains a pointer to an array

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;
, and then i try to initialize this node using the following function:

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]
. Does anyone have any idea of what's going on? Considering
current_node->node
is a pointer, that points to another pointer of type
TRIE_NODE
, shouldn't i be able to access it's values through bracket notation? (I've tried dereferencing it too, it doesn't compile)

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));
    ...
}