C struct with pointers initialization

2020-06-03 16:17发布

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?

1条回答
放荡不羁爱自由
2楼-- · 2020-06-03 16:42

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.

查看更多
登录 后发表回答