T
Tomás
Why do you care that there's padding? sizeof tells you all you need to
know doesn't it?
Well consider this:
(I'm still not adjusted to C, so forgive me if I use C++ idioms/styles which
I shouldn't use.)
#include <stdlib.h>
typedef struct Monkey {
int i;
char a[1];
} Monkey;
void SomeFunc( Monkey* const p_monkey )
{
/* Let's get a pointer to the second array element: */
char *pc1 = &p_monkey->a[1];
/* Now let's do that another way: */
char *pc2 = (char*) (p_monkey + 1);
/* ******************************** */
/* Now let's compare the addresses */
if ( pc1 != pc2 )
{
printf("We have padding at the end!");
}
}
int main(void)
{
//Let's say we want that array to
//consist of seven elements:
void* const p = malloc( sizeof(Monkey) + 6 );
Monkey* const p_monkey = (Monkey*)p;
p_monkey->i = 5;
p_monkey->a[0] = 'a';
p_monkey->a[1] = 'b';
p_monkey->a[2] = 'c';
p_monkey->a[3] = 'd';
p_monkey->a[4] = 'e';
p_monkey->a[5] = 'f';
p_monkey->a[6] = 'g';
SomeFunc( p_monkey );
free(p);
}
If there is indeed three bytes of padding at the end of this structure, then
the following l-value:
p_monkey->a[1]
refers to the first byte of padding.
However, the following l-value:
p_monkey + 1
refers to the first byte AFTER the three bytes of padding.
Therefore, it seems that there's not much benefit in the whole "array at the
end of a structure" strategy. It would be just as handy to do the following:
typedef struct Monkey { int i; } Monkey;
int main(void)
{
void* const p = malloc( sizeof(Monkey) + 7 );
Monkey* const p_monkey = (Monkey*)p;
/* Now if we want to access the array: */
char* p_array = (char*) (p_monkey + 1);
p_array[0] = 'a';
p_array[1] = 'b';
}
Then "SomeFunc" could play with the structure as follows:
void SomeFunc( Monkey* const p_monkey )
{
/* Let's get a pointer to the first array element: */
char *p = (char*) (p_monkey + 1);
/* Now access the array: */
p[0] = 'a';
}
It appears to me, that there would only be merit in the method of putting an
array at then end of a struct if the padding was put BEFORE the first array
element, as follows:
a) 4 bytes for "i"
b) 3 bytes of padding.
c) 1st element of the array.
-Tomás