Initialize/reset struct to zero/null

前端 未结 9 1821
攒了一身酷
攒了一身酷 2020-11-27 10:28
struct x {
    char a[10];
    char b[20];
    int i;
    char *c;
    char *d[10];
};

I am filling this struct and then using the values. On the n

9条回答
  •  暖寄归人
    2020-11-27 11:00

    The way to do such a thing when you have modern C (C99) is to use a compound literal.

    a = (const struct x){ 0 };
    

    This is somewhat similar to David's solution, only that you don't have to worry to declare an the empty structure or whether to declare it static. If you use the const as I did, the compiler is free to allocate the compound literal statically in read-only storage if appropriate.

提交回复
热议问题