Ignoring padding/alignment issues and given the following struct, what is best way to get and set the value of member_b without using the member name.
struct mystruct {
int member_a;
int member_b;
}
struct mystruct *s = malloc(sizeof(struct mystruct));
Put another way; How would you express the following in terms of pointers/offsets:
s->member_b = 3;
printf("%i",s->member_b);
My guess is to
- calculate the offset by finding the sizeof the member_a (
int) - cast the struct to a single word pointer type (
char?) - create an
intpointer and set the address (to*charpointer + offset?) - use my
intpointer to set the memory contents
but I get a bit confused about casting to a char type or if something like memset is more apropriate or if generally i’m aproching this totally wrong.
Cheers for any help
The approach you’ve outlined is roughly correct, although you should use
offsetofinstead of attempting to figure out the offset on your own. I’m not sure why you mentionmemset— it sets the contents of a block to a specified value, which seems quite unrelated to the question at hand.Here’s some code to demonstrate how it works: