Initialize/reset struct to zero/null

前端 未结 9 1785
攒了一身酷
攒了一身酷 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.

    0 讨论(0)
  • 2020-11-27 11:04

    Better than all above is ever to use Standard C specification for struct initialization:

    struct StructType structVar = {0};
    

    Here are all bits zero (ever).

    0 讨论(0)
  • 2020-11-27 11:05

    I believe you can just assign the empty set ({}) to your variable.

    struct x instance;
    
    for(i = 0; i < n; i++) {
        instance = {};
        /* Do Calculations */
    }
    
    0 讨论(0)
  • 2020-11-27 11:07

    enter image description hereTake a surprise from gnu11!

    typedef struct {
        uint8_t messType;
        uint8_t ax;  //axis
        uint32_t position;
        uint32_t velocity;
    }TgotoData;
    
    TgotoData tmpData = { 0 };
    

    nothing is zero.

    0 讨论(0)
  • 2020-11-27 11:08
     struct x myX;
     ...
     memset(&x, 0, sizeof(myX));
    
    0 讨论(0)
  • 2020-11-27 11:11

    In C, it is a common idiom to zero out the memory for a struct using memset:

    struct x myStruct;
    memset(&myStruct, 0, sizeof(myStruct));
    

    Technically speaking, I don't believe that this is portable because it assumes that the NULL pointer on a machine is represented by the integer value 0, but it's used widely because on most machines this is the case.

    If you move from C to C++, be careful not to use this technique on every object. C++ only makes this legal on objects with no member functions and no inheritance.

    0 讨论(0)
提交回复
热议问题