我有一个宏来计算我的C代码中的数组大小:
#define sizearray(a) (sizeof(a) / sizeof((a)[0]))
Run Code Online (Sandbox Code Playgroud)
当我测试它时,它适用于静态定义的数组,但对于动态定义的数组则不行(见下文).我不确定我理解为什么会这样.有没有办法计算堆上分配的数组的大小?
/* test sizearray macro */
void testSIZEARRAY(void)
{
/* test case for statically defined array */
int a[5] = {0,0,0,0,0};
assert(sizearray(a) == 5);
/* test case for dynamically defined array */
int *b;
b = calloc(5, sizeof(int));
assert(sizearray(b) == 5);
free(b);
}
Run Code Online (Sandbox Code Playgroud)