7

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 Answer 1

17

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.

Sign up to request clarification or add additional context in comments.

12 Comments

Will calloc correctly initialize NULL pointers ? I mean will all-bits 0 always mean NULL ?
My GCC (4.6.1) gives me a warning "missing initialiser" when I write = {0}. Are you sure that's legit?
@cnicutar: No. "Zero-initialisation" isn't the same as "null-initialisation". The underlying representation of a pointer whose value was assigned the null pointer literal needn't be 0. [C99:6.3.2.3/3]
@Kerrek: According to gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#Warning-Options, -Wextra enables -Wmissing-field-initializers, which warns about this, even though it acknowledges that they're implicitly initialized to zero.
@Zahy: You can't format comments other than with backticks, but feel free to amend your original post! Also, being "indeterminate" includes the possibility of being zero - there's just no guarantee.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.