Selhar Selhar - 6 months ago 18
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];

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


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