How to initialize a struct in accordance with C programming language standards

前端 未结 15 2901
予麋鹿
予麋鹿 2020-11-21 22:59

I want to initialize a struct element, split in declaration and initialization. This is what I have:

typedef struct MY_TYPE {
  bool flag;
  short int value;         


        
15条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 00:01

    as Ron Nuni said:

    typedef struct Item {
        int a;
        float b;
        char* name;
    } Item;
    
    int main(void) {
        Item item = {5, 2.2, "George"};
        return 0;
    }
    

    An important thing to remember: at the moment you initialize even one object/variable in the struct, all of its other variables will be initialized to default value.

    If you don't initialize the values in your struct (i.e. if you just declare that variable), all variable.members will contain "garbage values", only if the declaration is local!

    If the declaration is global or static (like in this case), all uninitialized variable.members will be initialized automatically to:

    • 0 for integers and floating point
    • '\0' for char (of course this is just the same as 0, and char is an integer type)
    • NULL for pointers.

提交回复
热议问题