Let's say my code is:
typedef stuct {
int x;
double y;
char z;
} Foo;
would x
, y
, and z
, be right next to each other in memory? Could pointer arithmetic 'iterate' over them?
My C is rusty so I can not quite get the program right to test this.
Here is my code in full.
#include <stdlib.h>
#include <stdio.h>
typedef struct {
int x;
double y;
char z;
} Foo;
int main() {
Foo *f = malloc(sizeof(Foo));
f->x = 10;
f->y = 30.0;
f->z = 'c';
// Pointer to iterate.
for(int i = 0; i == sizeof(Foo); i++) {
if (i == 0) {
printf(*(f + i));
}
else if (i == (sizeof(int) + 1)) {
printf(*(f + i));
}
else if (i ==(sizeof(int) + sizeof(double) + 1)) {
printf(*(f + i));
}
else {
continue;
}
return 0;
}
No, it is not guaranteed for struct
members to be contiguous in memory.
From §6.7.2.1 point 15 in the C standard (page 115 here):
There may be unnamed padding within a structure object, but not at its beginning.
Most of the times, something like:
struct mystruct {
int a;
char b;
int c;
};
Is indeed aligned to sizeof(int)
, like this:
0 1 2 3 4 5 6 7 8 9 10 11
[a ][b][padding][c ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With