使用嵌套结构时,我倾向于执行以下操作。我想知道这是否是structs
在这种特殊情况下初始化的正确方法,或者是否有更好的方法。
#include <string.h>
#include <stdlib.h>
typedef struct inner_struct {
char *name;
int account;
} inner;
typedef struct outer_struct {
int count;
char *company;
inner *my_inner;
} outer;
outer *
initialize_outer (size_t max) {
outer *out = malloc(sizeof (outer) * max);
if (out) {
memset(out, 0, sizeof *out * max);
out->count = 0;
out->company = NULL;
}
return out;
}
inner *
initialize_inner () {
inner *in = malloc(sizeof (inner));
if (in) {
memset(in, 0, sizeof *in);
in->account = 0;
in->name = NULL;
}
return in;
}
int main(int argc, char *argv[]){
int i;
size_t max_out = 20;
outer *my_out = initialize_outer(max_out);
for (i = 0; i<max_out;i++) {
my_out[i].my_inner = initialize_inner();
}
}