About default C struct values, what about this code?

后端 未结 8 1483
时光说笑
时光说笑 2020-12-31 15:27

I\'m trying to create structs with default values. I don\'t know how to accomplish this because every code that I see, is about initialising, and I would it for the natural

8条回答
  •  悲&欢浪女
    2020-12-31 16:06

    As you have probably learned from the other answers, in C you can't declare a structure and initialize it's members at the same time. These are different tasks and must be done separately.

    There are a few options for initializing member variables of a struct. I'll show a couple of ways below. Right now, let's assume the following struct is defined in the beginning of the file:

    struct stuff {
      int stuff_a;
      int stuff_b;
    };
    

    Then on your main() code, imagine that you want to declare a new variable of this type:

    struct stuff custom_var;
    

    This is the moment where you must initialize the structure. Seriously, I mean you really really must! Even if you don't want to assign specific values to them, you must at least initialize them to zero. This is mandatory because the OS doesn't guarantee that it will give you a clean memory space to run your application on. Therefore, always initialize your variables to some value (usually 0), including the other default types, such as char, int, float, double, etc...

    One way to initialize our struct to zero is through memset():

    memset(&custom_var, 0, sizeof(struct stuff));
    

    Another is accessing each member individually:

    custom_var.stuff_a = 0;
    custom_var.stuff_b = 0;
    

    A third option, which might confuse beginners is when they see the initialization of struct members being done at the moment of the declaration:

    struct stuff custom_var = { 1, 2 };
    

    The code above is equivalent to:

    struct stuff custom_var;
    custom_var.stuff_a = 1;
    custom_var.stuff_b = 2;
    

提交回复
热议问题