0

I am trying to understand the offset value of the c struct such as below:

typedef struct
{                      /* offset  */
   uint32_t MODER;     /* 0x00 */
   uint32_t OTYPER;    /* 0x04 */
   uint32_t OSPEEDR;   /* 0x08 */
   uint32_t PUPDR;     /* 0x0C */
   ... 
}GPIO_regDef_t;

GPIO_RegDef_t *pGPIOB = (GPIO_RegDef_t*) 0x40000000;

When storing 44 to OTYPER in such way

pGPIOB->OTYPER = 44; 

how does the compiler know it is writing to the address of

*(0x40000000 + 0x04) ?

In other words I don't understand the relationship between Uint32 and 0x04.

Could someone please explain?

Thanks,

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
taka
  • 5
  • 2
  • 2
    `uint32_t` is four bytes in length (it takes four bytes to store a 32-bit value). So, the next field would have to start at least four bytes after the beginning of the previous one. – Ouroborus Aug 03 '22 at 00:53
  • 1
    The compiler determines the offset of every struct member. – Barmar Aug 03 '22 at 00:56
  • Okay... so why 0x04 represents 4 bytes but not 4 bits ? – taka Aug 03 '22 at 01:35
  • Because we deal in _bytes_ when working with pointers. – paddy Aug 03 '22 at 01:54
  • You probably want to checkout `offsetof` in `stddef.h` instead of calculating these manually. – Neil Aug 03 '22 at 05:04
  • @taka - *"Okay... so why 0x04 represents 4 bytes but not 4 bits ?"* Because you use a computer that counts memory in bytes. It can be some other value on some other kind of CPU, doesn't have to be 4. – BoP Aug 03 '22 at 08:48
  • More generally there are specifications that describe how much of this is handled. See [Where do I find the current C or C++ standard documents?](https://stackoverflow.com/questions/81656/where-do-i-find-the-current-c-or-c-standard-documents) (though you may need more experience to parse the specification). – Ouroborus Aug 05 '22 at 05:28

0 Answers0