开发者

C struct with pointers initialization

开发者 https://www.devze.com 2023-03-27 19:58 出处:网络
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?

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 bo开发者_如何学Goard[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.

0

精彩评论

暂无评论...
验证码 换一张
取 消