将所有结构指针成员设置为 NULL

Setting all struct pointer members to NULL

如果我通过 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]);
    }
}

没有。 malloc 从不初始化分配的内存。来自 man page:

The memory is not initialized.

来自C标准,7.20.3.3 malloc函数:

The malloc function allocates space for an object ... whose value is indeterminate.

malloc() 函数从不初始化内存区域。您必须使用 calloc() 专门将内存区域初始化为零。您看到初始化内存的原因已解释 here.

您可以使用 static const 关键字来设置结构的成员变量。

#include

struct rabi 
{
int i;
float f;
char c;
int *p; 
};
int main ( void )
{

static const struct rabi enpty_struct;
struct rabi shaw = enpty_struct, shankar = enpty_struct;


printf ( "\n i = %d", shaw.i );
printf ( "\n f = %f", shaw.f );
printf ( "\n c = %d", shaw.c );
printf ( "\n p = %d",(shaw.p) );


printf ( "\n i = %d", shankar.i );
printf ( "\n f = %f", shankar.f );
printf ( "\n c = %d", shankar.c );
printf ( "\n p = %d",(shankar.p) );
return ( 0 );
}



Output:

 i = 0
 f = 0.000000
 c = 0
 p = 0

 i = 0
 f = 0.000000
 c = 0
 p = 0