I have the following test code:
#include <stdio.h>
struct prueba
{
long long c;
double xx;
int e;
float b;
short a;
char ff;
char d[5];
};
int main()
{
struct prueba hh[3];
printf("Size: %d\n\n", sizeof(struct prueba));
for (int j = 0; j != 3; ++j)
{
printf("%d\n", &hh[j].c);
printf("%d\n", &hh[j].xx);
printf("%d\n", &hh[j].e);
printf("%d\n", &hh[j].b);
printf("%d\n", &hh[j].a);
printf("%d\n", &hh[j].ff);
for (int i = 0; i != 5; ++i)
printf("%d\n", &hh[j].d[i]);
printf("\n");
}
return 0;
}
And it gives me 32 bytes as the size of the structure as a result. However, what I fail to understand is that some members have memory addresses that are not a multiple of their byte size. I compiled the test code on Windows, where my machine is 32-bit, and it threw me, for example, in the first member "c" a memory address that was not divisible by its size. I had read that the memory addresses of the members should be divisible by their size in bytes because it was more efficient for the processor, although I don't know the "why", I would like to know also if it is possible.
Let's modify your code a bit: we'll remove the compiler warnings , and we'll just show what's important:
Which shows the following result:
Well, we already see that it is fulfilled : all the members (except the last one) show
alineado: Si
.Okay. Now, let's modify your
struct
. Let's change the memberff
, fromchar
we will pass it toint
:Now the output is:
Still true: all (except the last one) keep showing
alineado: Si
.Well, you see that it is correct . It is true in all cases ... it appears not to be true in the last member because it
sizeof( X[] )
returns the size of the entire array .Very easy. The idea is that memory access is slow . So, what it is about is minimizing that number of accesses. And the data bus reads in discrete chunks of memory. If the bus is 32-bit, it will always read in multiples of 4: 0, 4, 8, 16, ...
If you want to read position 5, in reality it will always read from position 4. If the data fits, fine. But, if the data is not aligned correctly, you may have to access both addresses 4 and 8: 2 accesses, twice as long.