C struct with pointers initialization

后端 未结 1 863
無奈伤痛
無奈伤痛 2021-02-09 04:05

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?

相关标签:
1条回答
  • 2021-02-09 04:48

    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 讨论(0)
提交回复
热议问题