写C时,经常要用到计算数组长度,我一般用下面这种方法:
#define LEN(x) sizeof(x) / sizeof(x[0])
即利用库函数sizeof来计算数组长度,这种方法,对一维数组和多维数组都有效,如以下代码示例:
#include "stdio.h"#define LEN(x) sizeof(x) / sizeof(x[0])int main(int argc, char *argv[])
{int one[2] = {1, 1};int two[2][1] = {{1}, {2}};int three[3][2] = {{1, 2}, {1, 2}, {1, 2}};printf("%d\n", LEN(one));printf("%d\n", LEN(two));printf("%d\n", LEN(three));return 0;
}
这是运行结果: