Initialize/reset struct to zero/null

前端 未结 9 1786
攒了一身酷
攒了一身酷 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:13

    You can use memset with the size of the struct:

    struct x x_instance;
    memset (&x_instance, 0, sizeof(x_instance));
    
    0 讨论(0)
  • 2020-11-27 11:20

    Define a const static instance of the struct with the initial values and then simply assign this value to your variable whenever you want to reset it.

    For example:

    static const struct x EmptyStruct;
    

    Here I am relying on static initialization to set my initial values, but you could use a struct initializer if you want different initial values.

    Then, each time round the loop you can write:

    myStructVariable = EmptyStruct;
    
    0 讨论(0)
  • 2020-11-27 11:24

    If you have a C99 compliant compiler, you can use

    mystruct = (struct x){0};
    

    otherwise you should do what David Heffernan wrote, i.e. declare:

    struct x empty = {0};
    

    And in the loop:

    mystruct = empty;
    
    0 讨论(0)
提交回复
热议问题