我有一些包含数组的结构
struct mystruct_withArrays {
int foo;
int bar[MaxN];
int baz[MaxM];
}
以及它们与指针的等价物
struct mystruct_withPointers {
int foo;
int *bar;
int *baz;
}
我想避免双重定义。这是我想做一些东西作为模板
#define myStruct(M,N)
...
这样myStruct(MaxM,MaxN)
生成数组结构并myStruct(,)
生成带有指针的结构。
此外,我当然想对多个结构执行相同的技术,并实现从数组到指针的自动映射。最终用例可能如下
#include "mystructs.h"
//globals, for huge space usage
struct myStructA(1000,10000) hugeA;
struct myStructB(1024*1024) * hugeB;
void main(){
struct myStructA(,) smallA;
struct myStructB() smallB;
mapStruct(hugeA,smallA) //this is a macro
mapStruct(hugeB,smallB) //this is a macro
doSomething(smallA);
doSomethingMore(smallA,smallB);
doSomethingDetailed(smallB.qux);
}
哪里mapStruct(hugeA, smallA)
是明显的映射smallA.bar = hugeA.bar
等。扩展的代码将是:
struct myStructA(1000,10000) hugeA;
struct myStructB(1024*1024) hugeB;
struct mystructA_withArrays {
int foo;
int bar[1000];
int baz[10000];
} hugeA;
struct mystructB_withArrays * {
int qux[1048576];
int quux[1048576];
} hugeB;
void main(){
struct mystructA_withPointers {
int foo;
int * bar;
int * baz;
} smallA;
struct mystructB_withArrays {
int * qux;
int * quxx;
} smallB;
smallA.bar=hugeA.bar;
smallA.baz=hugeA.baz;
smallB.qux=hugeB.qux;
smallB.quxx=hugeB.quxx;
doSomething(smallA);
doSomethingMore(smallA,smallB);
doSomethingDetailed(smallB.qux);
}
如您所见,一般的想法是一些变量分配在堆栈之外,但仍然没有使用malloc,只是将它们声明为全局变量。即使在某些用例中,它们也是来自链接共享对象的外部全局变量。
编辑:关于内存性能,很难确定 malloc 结构比全局结构好还是差。它还取决于编译器的标志 -mcmodel