T'n'E
T'n'E

Reputation: 616

What does *(<type>*)(<constant>) mean?

I recently came across the following C-code:

*(STRUCT_T*)(0xC6)

STRUCT_T is a typedefed structure. Can someone explain what this means?

My guess: STRUCT_T* casts the address 0xC6 to a structure pointer and * then retrieves the value (struct) stored at the address 0xC6?

Upvotes: 2

Views: 624

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134326

Yes, you're correct but I guess, this question needs a little more elaborated answer for why we are doing this.

To start with, let's see what is done by the unary * operator. It dereferences it's operand based on the type of the operand. To elaborate in very simple terms,

  • *ptr, when ptr is of type char * will read sizeof(char) i.e., 1 bytes of data starting from ptr
  • *ptr, when ptr is of type int * will read sizeof(int) i.e., 4 bytes of data (on 32 bit system) starting from ptr

So, by saying *(STRUCT_T*)(0xC6), we're enforcing

  • treat the pointer (address) 0xC6 as a pointer to type STRUCT_T.
  • dereference the same to get the value of type STRUCT_T.

Upvotes: 2

Related Questions