memset() or value initialization to zero out a struct?

后端 未结 8 2142
你的背包
你的背包 2020-11-27 10:29

In Win32 API programming it\'s typical to use C structs with multiple fields. Usually only a couple of them have meaningful values and all others have to be zer

相关标签:
8条回答
  • 2020-11-27 11:20

    I would use value initialization because it looks clean and less error prone as you mentioned. I don't see any drawback in doing it.

    You might rely on memset to zero out the struct after it has been used though.

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

    If your struct contains things like :

    int a;
    char b;
    int c;
    

    Then bytes of padding will be inserted between "b" and "c". memset() will zero those, the other way will not, so there will be 3 bytes of garbage (if your ints are 32 bits). If you intend to use your struct to read/write from a file, this might be important.

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