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
int
pointer and set the address (to *charpointer + offset
?)
- use my
int
pointer 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
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…