c - 用于获取数组中的数字元素或在变量上使用时仅返回 1 的通用宏?

标签 c macros sizeof c99

在 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/

相关文章:

c - 数组的数组和多维数组有什么区别?

python - 当多次调用具有多个参数的函数时,Python中有什么好方法可以减少代码重复?

c++ - 为什么要定义sizeof实现的结果?

c++ - 这个 "size of array"模板函数是如何工作的?

c++ - 无法使 SHGetKnownFolderPath() 函数正常工作

c - 有没有办法让链接器从库中拉出目标文件的一部分进行链接?

c - 汉明重量(数字中1的个数)混合C与组件

scala - 如何在宏中重用定义 (AST) 子树?

c++ - 了解带有常量的预处理器宏

c - 从 size_t 转换为 int 时没有警告