如果我通过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]);
}
}
答案 0 :(得分:6)
malloc()
函数从不初始化内存区域。您必须使用calloc()
将内存区域专门初始化为零。您看到初始化内存的原因解释为here.
答案 1 :(得分:4)
答案 2 :(得分:1)
您可以使用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