在 C 语言中,用于获取数组元素数量的宏是众所周知的,如下所示:
uint32_t buffer[10];
#define ARRAY_SIZE(x) sizeof(x)/sizeof(x[0])
size_t size = ARRAY_SIZE(buffer);
问题是,是否有任何通用宏可以获取数组元素或在变量上使用时仅返回一个元素?我的意思是宏的以下用法:
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
有人知道解决办法吗?
我编辑了我的问题,因为它的表述错误,顺便说一句,我知道我可以使用:
sizeof(variable)/sizeof(uint32_t)
问题是如何将它组合在一个宏中,或者内联函数可能是更好的解决方案?
最佳答案
您可以使用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;
}
输出(在我的机器上):
4
40
10
关于您所做的编辑:
你can't perform type checking in C ,因此你无法检查你传递的是数组还是变量。
关于c - 用于获取数组中的数字元素或在变量上使用时仅返回 1 的通用宏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26141517/