How to initialize a struct in accordance with C programming language standards

前端 未结 15 2708
予麋鹿
予麋鹿 2020-11-21 22:59

I want to initialize a struct element, split in declaration and initialization. This is what I have:

typedef struct MY_TYPE {
  bool flag;
  short int value;         


        
15条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-21 23:45

    I've been looking for a nice way to initialize my struct, and I've got to using the below (C99). This lets me initialize either a single structure or an array of structures in the same way as plain types.

    typedef struct {
        char *str;
        size_t len;
        jsmntok_t *tok;
        int tsz;
    } jsmn_ts;
    
    #define jsmn_ts_default (jsmn_ts){NULL, 0, NULL, 0}
    

    This can be used in the code as:

    jsmn_ts mydata = jsmn_ts_default; /* initialization of a single struct */
    
    jsmn_ts myarray[10] = {jsmn_ts_default, jsmn_ts_default}; /* initialization of
                                                        first 2 structs in the array */
    

提交回复
热议问题