In C language macro for getting number of array elements is well known and looks like this:
在C语言中,获取数组元素的数量是众所周知的,如下所示:
uint32_t buffer[10];
#define ARRAY_SIZE(x) sizeof(x)/sizeof(x[0])
size_t size = ARRAY_SIZE(buffer);
The question is, is there any universal macro for getting array elements or returning just one when it's used on variable ? I mean following usage of macro :
问题是,是否有一个通用的宏来获取数组元素,或者在变量使用时只返回一个?我的意思是在使用宏的时候
uint32_t buffer[10];
uint32_t variable;
#define GET_ELEMENTS(x) ???
size_t elements_of_array = GET_ELEMENTS(buffer); // returns 10
size_t elements_of_variable = GET_ELEMENTS(variable); // returns 1
Does anybody know the solution ?
有人知道答案吗?
I've edited my question because it was wrongly formulated, BTW I know that I can use :
我已经编辑了我的问题,因为它被错误地表述了,我知道我可以使用:
sizeof(variable)/sizeof(uint32_t)
Question is how to combine it in one macro or maybe inline function is better solution ?
问题是如何在一个宏或内联函数中组合它是更好的解决方案?
1 个解决方案
#1
3
You could use sizeof
, like this:
你可以使用sizeof,像这样:
#include <stdio.h>
int main(void)
{
unsigned int buffer[10];
// size of one unsigned int
printf("%zu\n", sizeof(unsigned int));
// this will print the number of elements of buffer * size of an unsigned int
printf("%zu\n", sizeof(buffer));
// you have a mistake
// the following printf() gives you the number of elements
printf("%d\n", sizeof(buffer)/sizeof(buffer[0]));
return 0;
}
Output (on my machine):
输出(在我的机器上):
4
40
10
Regarding the edit you made:
关于你的编辑:
You can't perform type checking in C, thus you can not check if what you pass is an array or a variable.
您不能在C中执行类型检查,因此您不能检查您传递的是一个数组还是一个变量。
#1
3
You could use sizeof
, like this:
你可以使用sizeof,像这样:
#include <stdio.h>
int main(void)
{
unsigned int buffer[10];
// size of one unsigned int
printf("%zu\n", sizeof(unsigned int));
// this will print the number of elements of buffer * size of an unsigned int
printf("%zu\n", sizeof(buffer));
// you have a mistake
// the following printf() gives you the number of elements
printf("%d\n", sizeof(buffer)/sizeof(buffer[0]));
return 0;
}
Output (on my machine):
输出(在我的机器上):
4
40
10
Regarding the edit you made:
关于你的编辑:
You can't perform type checking in C, thus you can not check if what you pass is an array or a variable.
您不能在C中执行类型检查,因此您不能检查您传递的是一个数组还是一个变量。