我有一个关于为结构创建和分配空间的问题,以及什么是“更好”的方法。
假设我们有一堆参数,基于这些参数,我们想创建一个结构。不是直接存储所有参数,而是以某种方式处理它们并存储值。
示例:
typedef struct {
int op;
int res;
} Result;
int operation = 0; // 0 = addition, 1 = multiplication
int a = 2, int b = 3;
Result r;
r.op = operation;
if (operation == 0) {
r.res = a+b;
else if(operation == 1) {
r.res = a*b;
else {
...etc...
}这些操作可能比这更复杂,并且可能有更多的参数来定义最终的结构。所以我想创建一个函数
create_structure(arg1, arg2, arg3, ..., argn) {
switch(arg1) {
case 0: struct_function0(arg1, arg2, arg3, ..., argn); break;
case 1: struct_function1(arg1, arg2, arg3, ..., argn); break;
...
case m: struct_functionm(arg1, arg2, arg3, ..., argn); break;
}
}所有这些函数都可以具有与“create_structure”相似的结构,并将形成“函数创建树”,在该树中,我们总是根据参数选择一个分支,直到我们到达某个最终将创建我们结构的函数。我们还希望树的“根”返回一个指针,指向存储此结构的内存位置。
问题是如何从函数创建树的“叶子”返回创建的结构。
第一个选项是始终从内部函数返回结构,然后在树的根中为该结构和memcpy所有内容分配内存:
MyStruct* create_structure(arg1, arg2, arg3, ..., argn) {
MyStruct s;
switch(arg1) {
case 0: s = struct_function0(arg1, arg2, arg3, ..., argn); break;
case 1: s = struct_function1(arg1, arg2, arg3, ..., argn); break;
...
case m: s = struct_functionm(arg1, arg2, arg3, ..., argn); break;
}
MyStruct* p_s = malloc(sizeof(MyStruct));
memcpy(p_s, &s, sizeof(MyStruct));
return p_s
}另一种可能是将指向根中结构的指针放错位置,然后将其作为参数发送到树的所有“分支”。像这样
MyStruct* create_structure(arg1, arg2, arg3, ..., argn) {
MyStruct* p_s = malloc(sizeof(MyStruct));
switch(arg1) {
case 0: struct_function0(p_s, arg1, arg2, arg3, ..., argn); break;
case 1: struct_function1(p_s, arg1, arg2, arg3, ..., argn); break;
...
case m: struct_functionm(p_s, arg1, arg2, arg3, ..., argn); break;
}
return p_s;
}在第二个变种中,我们将通过树中的所有函数传递参数p_s,直到到达一个叶。
还有一种可能的第三种选择,其中malloc可以在树的叶子中。
这些可能性中哪一种是首选的?还有没有别的选择?
发布于 2018-06-01 19:28:00
实际上,你根本不需要malloc。一种可能是将指向结构的指针传递给所有函数
void create_structure(MyStruct* s, arg1, ...)
{
...
}
MyStruct p_s;
create_structure(&s, arg1, arg2, ...);你也可以返回一个你的结构的副本,如果结构的大小很小,那么它就不是繁重的操作。
MyStruct create_structure(arg1, arg2, arg3, ..., argn) {
MyStruct p_s;
switch(arg1) {
case 0: p_s = struct_function0(arg1, arg2, arg3, ..., argn); break;
case 1: p_s = struct_function1(arg1, arg2, arg3, ..., argn); break;
...
case m: p_s = struct_functionm(arg1, arg2, arg3, ..., argn); break;
}
return p_s;
}https://stackoverflow.com/questions/50642220
复制相似问题