我有一个宏在我的C码计算数组大小:计算数组大小
#define sizearray(a) (sizeof(a)/sizeof((a)[0]))
当我测试它,它工作正常为静态定义的阵列,但不因此对动态定义的阵列(见下面)。不知道我明白为什么会这样。有什么方法可以计算堆中分配的数组的大小吗?
/* 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);
}
sizeof在编译时进行评估。所以,不,那不可能。 – ordag 2012-01-05 22:26:54
[如何获取C中动态创建的结构数组的长度?]的可能重复(http://stackoverflow.com/questions/8717267/how-to-get-the-length-of-a-dynamically- (c) – dasblinkenlight 2012-01-05 22:27:54
[计算数组的大小]的可能的重复(http://stackoverflow.com/questions/720077/calculating-size-of-an-array) – 2012-01-05 22:49:52