One solution to print the offset of the checksum
field in the info
struct, is to use the macros typeof
and offsetof
:
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
typedef struct
{
struct {
int a;
} something;
struct {
int a;
int b;
int c[42];
uint32_t checksum;
int padding[10];
} info[2];
// ...
} S;
int main(void)
{
S s;
printf("%lu\n", offsetof(typeof(s.info[0]), checksum));
return 0;
}
Unfortunately, typeof
is not standard, so I am looking for a more convenient way to write the above example without having to declare info
outside from S
.
Why I am trying to do this?
I have a big structure that represent the content of a FLASH memory that represent blocks of information. Each of these blocks have a checksum that I would like to check:
if (s.info[0].checksum != checksum(s.info[0], offsetof(typeof(s.info[0]), checksum))) {
printf("Oops\n");
}
The writing is not portable because of typeof
.