gpt4 book ai didi

c - 在 C 中初始化嵌套结构的正确方法

转载 作者:太空宇宙 更新时间:2023-11-04 05:42:51 24 4
gpt4 key购买 nike

当使用嵌套结构时,我倾向于做如下的事情。我想知道在这种特殊情况下这是否是初始化 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();
}
}

最佳答案

为什么不使用calloc():

outer *
initialize_outer (size_t max) {
return calloc(max, sizeof(outer));
}

inner *
initialize_inner (size_t max) {
return calloc(max, sizeof(inner));
}

但是,为了简单起见,我可能会这样做:

typedef struct outer_struct {
int count;
char *company;
inner my_inner[];
} outer;

outer *
initialize (size_t max_out, size_t max_in) {
return calloc(1, (sizeof (outer) + sizeof (inner) * max_in) * max_out);
}

int main(int argc, char *argv[]){
size_t max_out = 20, max_in = 10;
outer *my_out = initialize(max_out, max_in);
...
}

关于c - 在 C 中初始化嵌套结构的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13872917/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com