user8565662
user8565662

Reputation: 127

Using offsetof to perform pointer arithmetic example

I was trying to learn about acessing struct memebers by using the offsetof() macro and I ran into this example How can I access structure fields by name at run time? This line:

//Set the value of 'a' using pointer arithmetic
*(int *)((char *)structp + offsetf) = 5;

gives me trouble. Why is the pointer being cast to a char * and then back to an int *?

Upvotes: 1

Views: 378

Answers (2)

AnT stands with Russia
AnT stands with Russia

Reputation: 320451

Firstly, the struct pointer has to be cast to "byte pointer" type, since offsetf most likely contains the byte-offset of the desired struct field. Because of this cast, pointer arithmetic in (char *)structp + offsetf subexpression is performed in terms of char objects (in terms of bytes), exactly as we want it.

Secondly, the above subexpression gives us a pointer of type char * that points to the desired data field. But in reality that data field apparently has type int. So, in order to gain access to that data field we have to cast our char * pointer to the proper int * type. After that we can perform read (or write) access to that data field by using the unary * operator.

In your case value 5 is written into an int data field located at byte-offset offsetf inside an object pointed by structp.

Upvotes: 3

Nicolas Guerin
Nicolas Guerin

Reputation: 366

Because in order: you derreference * something casted into int* so you can acess the data and set it to 5.

The cast into char * is because casting char * to int * is easy due to the fact that every char has an integer value.

Upvotes: 0

Related Questions