I am stumped by an apparent error in my use of offsetof() within an X macro. The code below shows two examples of a rather simple structure, one defined explicitly, and another defined using an X macro. The offsets of each structure field within both structures are then printed to the screen. As you can see in comments below, the c field in the structure defined with X macro shows an incorrect offset.
I believe this is a print problem. Can someone please shed some light on this mystery?
#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;
}