I have a question regarding structs in C. So when you create a struct, you are essentially defining the framework of a block of memory. Thus when you create an instance of a str
When you use the .
operator, the compiler translates this to an offset inside the struct
, based on the size of the fields (and padding) that precede it.
For example:
struct Car {
char model[52];
int doors;
int GasMilage;
};
Assuming an int
is 4 bytes and no padding, the offset of model
is 0
, the offset of doors
is 52
, and the offset of GasMilage
is 56.
So if you know the offset of the member, you could get a pointer to it like this:
int *GasMileagePointer = (int*)((char *)&carInstance + offsetInBytes(GasMile));
The cast to char *
is necessary so that pointer arithmetic goes 1 byte at a time instead of 1 sizeof(carInstance)
at a time. Then the result needs to be casted to the correct pointer type, in this case int *