0

I'm using following code:

#define OFFSETOF(_s, _m) ((uint32_t)(uint32_t *)(&(((_s *)0)->_m)))

typedef struct test
{
    uint16_t param0;
    uint8_t param1;
} test;

uint32_t uStartAddr = OFFSETOF(test, param1);

But I get that error:

error: cast from pointer to integer of different size
Swordfish
  • 12,971
  • 3
  • 21
  • 43
mujtaba
  • 195
  • 2
  • 14
  • 4
    Why are you making up your own `OFFSETOF`? `stddef.h` already has one that is bug free. – StoryTeller - Unslander Monica May 11 '19 at 18:17
  • 3
    You should be using `muintptr_t` instead of `uint32_t` because you're on a system where pointers are 64 bits, not 32 bits as you assume. This is why you should use the standard macro, too, rather than try to devise your own — at least in code that's supposed to be 'production quality' rather than an exercise. The `offsetof()` macro is peculiar; it can't be a function. But taking the address of an offset from address 0 is iffy — it will usually work, but certainly isn't guaranteed by the standard. That's why the implementation defines `offsetof`; it knows what can be done. – Jonathan Leffler May 11 '19 at 18:27
  • I can't type — I meant `uintptr_t`, not `muintptr_t`. Sorry! – Jonathan Leffler May 11 '19 at 19:09

1 Answers1

2

Your platform has pointers that are larger than 32 bits. Furthermore, the type of the offsetof() expression should be size_t. You should either:

  • use the standard offsetof macro from <stddef.h>

  • if your compiler does not provide the above definition, use this alternative:

    #define OFFSETOF(_s, _m) ((size_t)(&((_s *)0)->_m))
    
  • if you still have problems, try this one:

    #define OFFSETOF(_s, _m) ((size_t)((char*)&((_s *)0)->_m - (char*)0))
    
chqrlie
  • 131,814
  • 10
  • 121
  • 189