简体   繁体   中英

C struct with pointers initialization

When a struct that contains an array of struct pointers is instantiated, am I guaranteed that all pointers in the struct array member will be set to NULL ?

Here's 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 struct, will the elements of mmNode.children always be set to NULL ?

It depends how you initialise your struct.

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 just have random junk values. "Default-initialized" means that all members will be initialized to 0, which for pointer members will be equivalent to NULL . "Zero-initialized" means that everything will be set, bitwise, to 0. This will only work on platforms where NULL is represented with bitwise 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM