What value have int fields in struct not initializ

2019-05-25 08:48发布

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

标签: c struct char int
3条回答
时光不老,我们不散
2楼-- · 2019-05-25 09:09

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.

查看更多
祖国的老花朵
3楼-- · 2019-05-25 09:13

to be on safe side you should intialize your varibales to 0 yourself depending upon compiler it might pick garbage value as well

查看更多
等我变得足够好
4楼-- · 2019-05-25 09:16

If you define an object with an initializer, it's initialized to the specified value. If you only specify values for some members, the others are initialized to zero (meaning 0 for integers (including characters), 0.0 for floating-point values, and NULL for pointers).

If you define an object without an initializer, all members are implicitly initialized to zero if the object has static storage duration, i.e., if it's defined outside any function or if it's defined with the static keyword.

An object defined inside a function without the static keyword has automatic storage duration. Such objects, if not explicitly initialized, start off with garbage values. (If you happen to see such objects seemingly initialized to zero, remember that zero can be just as much a garbage value as anything else.)

You asked:

Are the integer fields (number and year) initialized to 0 by default when the other char fields are initialized but not these two?

but the code in your question doesn't initialize the char[] fields. See pmg's answer, which shows some good examples, but doesn't currently mention the static vs. automatic distinction.

查看更多
登录 后发表回答