我正在创建一个使用vCard struct
的应用程序。目前,此struct
看起来像这样:
typedef struct {
char *version;
char **names;
char *formatted_name;
char *nickname;
char *organisation;
char *title;
struct { /* Emails */
char *global_type;
char *type;
char *address;
/* Meant to be a boolean which C doesn't have -_- */
unsigned preferred : 1;
} *emails;
struct { /* Phones */
char *type;
char *number;
unsigned preferred : 1;
} *phones;
struct { /* Addresses */
char *type;
char *street;
char *city;
char *postal_code;
char *country;
unsigned preferred : 1;
} *addresses;
time_t birthday;
struct { /* Custom Fields */
char *field_name;
union {
/* Single value */
int i;
float f;
double d;
time_t t;
struct {
char *global_type;
char *type;
char *address;
/* Meant to be a boolean which C doesn't have -_- */
unsigned preferred : 1;
} email;
struct {
char *type;
char *number;
unsigned preferred : 1;
} phone;
struct {
char *type;
char *street;
char *city;
char *postal_code;
char *country;
unsigned preferred : 1;
} address;
char *s;
/* Multiple values */
int *is;
float *fs;
double *ds;
time_t *ts;
struct {
char *global_type;
char *type;
char *address;
/* Meant to be a boolean which C doesn't have -_- */
unsigned preferred : 1;
} *emails;
struct {
char *type;
char *number;
unsigned preferred : 1;
} *phones;
struct {
char *type;
char *street;
char *city;
char *postal_code;
char *country;
unsigned preferred : 1;
} *addresses;
char **ss;
} field_value;
} *custom_fields;
} vCard;
这个很庞大,需要很多记忆。我也用了很多指针。是否有更好,更清晰的方式来声明struct
?感谢。
另外,在union
s中使用struct
是一种好习惯,反之亦然?
答案 0 :(得分:8)
是的!拆分结构! (就像有一个巨大的功能。)
typedef struct {
char *global_type;
char *type;
char *address;
/* Meant to be a boolean which C doesn't have -_- */
unsigned preferred : 1;
} vCardEmail;
...
typedef struct { /* Custom Fields */
char *field_name;
union {
/* Single value */
int i;
float f;
double d;
time_t t;
vCardEmail email;
vCardPhone phone;
vCardAddress address;
char *s;
/* Multiple values */
int *is;
float *fs;
double *ds;
time_t *ts;
vCardEmail *emails;
vCardPhone *phones;
vCardAddress *addresses;
char **ss;
} field_value;
} vCardCustomField;
typedef struct {
char *version;
char **names;
char *formatted_name;
char *nickname;
char *organisation;
char *title;
vCardEmail *emails;
vCardPhone *phones;
vCardAddress *addresses;
time_t birthday;
vCardCustomField *custom_fields;
} vCard;