将所有struct指针成员设置为NULL

de3*_*z1e 2 c null struct pointers members

如果我通过malloc设置指向结构的指针指向内存块,那么所有成员是否会初始化为各自的默认值?如int为0,指针为NULL?我看到他们根据我编写的示例代码做了,所以我只是想让某人确认我的理解.感谢您的投入.

#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
#include <stdlib.h>

typedef struct node
{
    bool value;
    struct node* next[5];
}
node;

int main(void)
{
    node* tNode = malloc(sizeof(node));

    printf("value = %i\n", tNode->value);

    for (int i = 0; i < 5; i++)
    {
        if (tNode->next[i] == NULL)
            printf("next[%i] = %p\n", i, tNode->next[i]);
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 6

malloc()函数永远不会初始化内存区域.您必须使用calloc()专门将内存区域初始化为零.这里解释你看到初始化内存的原因.