c - x 宏打印错误的 offsetof() 信息

标签 c macros printf c-preprocessor offsetof

在 X 宏中使用 offsetof() 时,我被一个明显的错误所困扰。下面的代码显示了两个相当简单的结构示例,一个是显式定义的,另一个是使用 X 宏定义的。然后,两个结构中每个结构字段的偏移量都会打印到屏幕上。正如您在下面的注释中看到的,使用 X 宏定义的结构中的 c 字段显示了不正确的偏移量。

我认为这是打印问题。有人可以解释一下这个谜团吗?

#include <stdio.h>
#include <stdlib.h>

const char fmt[] = "%-5s 0x%04x(%05d)\n";

#define i(s, f) \
    #f, \
    offsetof(s, f), \
    offsetof(s, f)

int main(void)
{
    /**********************************
    METHOD1 - CORRECTLY PRINTS

        a     0x0000(00000)
        b     0x0004(00004)
        c     0x0008(00008)
        d     0x0030(00048)

    **********************************/
    typedef struct {
        uint32_t a;
        uint32_t b;
        uint32_t c[10];
        uint32_t d;
    } struct1;

    printf(fmt, i(struct1, a));
    printf(fmt, i(struct1, b));
    printf(fmt, i(struct1, c));
    printf(fmt, i(struct1, d));

    printf("\n");

    /**********************************
    METHOD2 - PRINTS WRONG INFO

        a     0x0000(00000)
        b     0x0004(00004)
        c[10] 0x0030(00048)  <== WRONG
        d     0x0030(00048)

    **********************************/

    #define FIELDS \
        X(uint32_t, a,     "") \
        X(uint32_t, b,     "") \
        X(uint32_t, c[10], "") \
        X(uint32_t, d,     "") \

    typedef struct {
    #define X(type, name, descr) type name;
        FIELDS
    #undef X
    } struct2;

    #define X(type, name, descr) printf(fmt, i(struct2, name));
        FIELDS
    #undef X

    return 0;
}

最佳答案

在第二个 X 宏中:

  #define X(type, name, descr) printf(fmt, i(struct2, name));
  FIELDS

这扩展为:

printf(fmt, "a", offsetof(struct2, a), offsetof(struct2, a));
printf(fmt, "b", offsetof(struct2, b), offsetof(struct2, b));
printf(fmt, "c[10]", offsetof(struct2, c[10]), offsetof(struct2, c[10]));
printf(fmt, "d", offsetof(struct2, d), offsetof(struct2, d));

offsetof(struct2, c[10]) 显然与 offsetof(struct2, c) 不同。

关于c - x 宏打印错误的 offsetof() 信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45204325/

相关文章:

c - 如何在另一个函数中嵌套 fprintf

c - 如何将二进制数据添加(和使用)到已编译的可执行文件中?

c - 为什么使用此代码创建的文本文件具有字符集 == 二进制?

c - 内联函数与宏函数

c - S_ISREG 宏未定义

c - printf() 仅在 while 循环期间打印空值

c - 立即分配指针和指针对象

c - 在哪里可以找到 math.h 中函数的源代码?

c++ - 如何为相同的预处理程序变量编译C++

带有外来字符的 php sprintf()?