c - 如何获取结构中的成员数?

标签 c runtime structure

我想计算结构中的成员数。 例如:

typedef struct
{
    char    MrChar;
    int MrInt;
    long    MrLong;
} Bg_Typedef;
Bg_Typedef FooStr;

我创建了一个函数原型(prototype),它应该返回结构中的成员数

int NumberOfMem(Bg_Typedef *psStructure); 

=> NumberOfMem(&FooStr) 应该返回 3

最佳答案

可以用X_MACRO来完成的。

做这样的事情:

#define X_BG_MEMBERS \
    X(char, MrChar) \
    X(int, MrInt) \
    X(long, MrLong)

typedef struct {
#define X(type, member) type member;
    X_BG_MEMBERS
#undef X
} Bg_Typedef;

Bg_Typedef FooStr;

定义一个计算成员数量的函数。也可以只是一个变量,但是要使变量static const,这样它就不会被覆盖

static int
bg_members_count() {
    #define X(_, __) +1
    static int COUNT = 0
    X_BG_MEMBERS;
    #undef X
    
    return COUNT;
}

现在你可以在 main 中做这样的事情:

#include <stdio.h>
...

int main() {
    printf("The number of members defined in Bg_Typedef is %d\n", bg_members_count());
}

你应该得到这样的东西:

The number of members defined in Bg_Typedef is 3

您可能还只想要一个常量,因此您可以执行以下操作

#define X(_, __) +1
static const int COUNT = X_BG_MEMBERS;
#undef X

替代模式

为了避免有很多 #define X... 后跟 #undef X,做这样的事情可能是有益的:

#define X_BG_MEMBERS(X) \
    X(char, MrChar) \
    X(int, MrInt) \
    X(long, MrLong)

#define BG_STRUCT_FIELD(type, field) type field;
#define BG_COUNT_MEMBER(_, __) +1

typedef struct {
  X_BG_MEMBERS(BG_STRUCT_FIELD)
} Bg_Typedefarguably;

static int
bg_members_count() {
    static int COUNT = X_BG_MEMBERS(BG_COUNT_MEMBER);    
    return COUNT;
}

// OR constant
// static const int COUNT = X_BG_MEMBERS(BG_COUNT_MEMBER);

它的工作原理与上面的相同,但应该明显更具可读性。参见 ref .

关于c - 如何获取结构中的成员数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12194793/

相关文章:

c - 发送消息不起作用

compiler-errors - 编译错误与运行时错误

ms-access - 添加可信位置以 Access 运行时

c++ - 结构 C++ ,动态名称构造

在 C 中将字符串转换为 float ?

c - 错误 "malloc: *** error for object 0x7b: pointer being freed was not allocated"可能是什么原因

在 Mac 终端中编译并运行 Sublime Text 文件

检查数组中未初始化的结构

java - 防止启动 java 应用程序的多个实例

c - 结构在另一个结构中的使用