结构体中的int字段未初始化什么值? [英] What value have int fields in struct not initialized yet?
问题描述
在程式码中:
...
#define MAXELEMNTS 100
struct book
{
int number;
char name [31];
char author [31];
int year;
char publisher [31];
};
struct book bkStruct [MAXELEMENTS];
...
字段(数字和年份)默认初始化为0时,其他的char字段初始化,但不是这两个?或者他们有神知道什么价值?在我的经验,他们有值= 0,但我不知道是这个一般规则,所以我必须确定!
没有部分初始化这样的东西。
如果通过为单个成员指定值来初始化结构,所有其他成员将自动初始化(适当种类的
0
)。 struct book
{
int number;
char name [31];
char author [31];
int year;
char publisher [31];
};
struct book book1; //没有初始化
struct book book2 = {.author =pmg}; //初始化所有的book2
struct book bkStruct1 [MAXELEMENTS]; // uninitialized array
struct book bkStruct2 [MAXELEMENTS] = {0}; // initialized array
//(每个元素的每个成员)
:一些实现可能会抱怨丢失大括号上的完美合法的数组初始化。这是这些实现的问题。
In the code: ...
#define MAXELEMNTS 100
struct book
{
int number;
char name[31];
char author[31];
int year;
char publisher[31];
};
struct book bkStruct[MAXELEMENTS];
...
Are the integer fields (number and year) initialized to 0 by default when the other char fields are initialized but not these two? Or do they have god-knows-what value? In my experience they do have value = 0, but I am not sure is this general rule so I must be sure!
Best regards, Papo
In C there is no such thing as "partial initialization".
If a struct is initialized by specifying a value for a single member, all the other members are automagically initialized (to 0
of the proper kind).
struct book
{
int number;
char name[31];
char author[31];
int year;
char publisher[31];
};
struct book book1; // no initialization
struct book book2 = { .author = "pmg" }; // initialization of ALL of book2
struct book bkStruct1[MAXELEMENTS]; // uninitialized array
struct book bkStruct2[MAXELEMENTS] = {0}; // initialized array
// (every member of every element)
Note: some implementations may complain about missing braces on the perfectly legal array initialization. That is a problem with those implementations.
这篇关于结构体中的int字段未初始化什么值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!