有以下代码(C99):
#define MAX_ALLOCATIONS 2
#if !defined(ALLOCATIONS)
#define ALLOCATIONS {{1, 0, 0, 64},{1, 0, 0, 32}}
#endif
struct allocation
{
int thread_count_;
int node_run_;
int node_alloc_;
int size_alloc_;
};
static struct allocation allocations[MAX_ALLOCATIONS] = ALLOCATIONS;
编译此代码时,可以传递如下内容:-D'ALLOCATIONS={{1, 0, 0, 8},{1, 0, 0, 16},{1 , 0, 0, 4}}'
。
是否有可能获得一个可以计算分配数量的宏?例如,当它得到 {{1, 0, 0, 8},{1, 0, 0, 16},{1, 0, 0, 4}}
时,它应该计算 3 >。这将允许摆脱上面代码中的MAX_ALLOCATIONS
。
是的,最简单的方法是将 -DMAX_ALLOCATIONS=3
与 -D'ALLOCATIONS={{1, 0, 0, 8},{1, 0, 0, 16},{1, 0, 0, 4}}'
,但对于用户来说很容易出错。
谢谢
最佳答案
定义数组allocations
时,不需要使用MAX_ALLOCATIONS
。
您需要做的就是将 ALLOCATIONS
定义为元素,数组的大小将自动确定。
当您在代码中需要该数组的大小时,请使用此宏,它将给出数组中元素的数量分配
:
#define MAX_ALLOCATIONS (sizeof(allocations)/sizeof(allocations[0]))
这是一个常数值。
关于计算 C 中静态数组初始化的元素数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36700227/