C struct with pointer initialization

When a structure is created containing an array of pointers to the structure, I'm sure that all pointers in the struct array element will be set to NULL ?

Here is an example struct:

 typedef struct mmNode { int val; int board[2][NUM_PITS+1]; int side; struct mmNode* children[NUM_PITS+1]; } mmNode; 

IE: If I create an instance of the mmNode structure, will the mmNode.children elements always be set to NULL ?

+7
source share
1 answer

It depends on how you initialize your structure.

 mmNode a; // Everything default-initialized void foo() { static mmNode b; // Everything default-initialized mmNode c; // Nothing initialized mmNode d = { 0 }; // Everything default-initialized mmNode *p = malloc(sizeof(*p)); // Nothing initialized mmNode *q = calloc(1, sizeof(*q)); // Everything zero-initialized } 

“Nothing initialized” means that all members will only have random spam values. "Default-initialized" means that all members will be initialized to 0, which is equivalent to NULL for pointer elements. "Zero-initialized" means that everything will be set, bitwise, to 0. This will only work on platforms where NULL appears to be bitwise 0.

+16
source

All Articles