Search code examples
cpointersstructdeclarationcompound-literals

C Empty Struct Pointer on Stack


I would like to initialize a struct with all fields as zero and immediately assign it to a pointer. The struct will only need to be used within static functions whose lifetime is completely contained within the calling function.

This is the line I currently have

move_stats *mv_s = (move_stats *){0};

The struct is defined in a header file as

typedef struct {
  byte open_threes;
  byte open_fours;
  byte half_open_fours;
  bool overline;
  bool five;
} move_stats;

byte is an alias for unsigned char. Will this create the struct in the way I want it to as written? I could not find a question exactly like this, apologies if it is a duplicate.


Solution

  • Your compound ;literal defines a null pointer instead of an object of the structure type

    move_stats *mv_s = (move_stats *){0};
    

    Instead write

    move_stats *mv_s = &(move_stats){0};