C program with two results.

I have this program that I execute into UNIX UX and after into UNIX AIX. The program are just below:

#include <stdio.h>

struct A
{
double d;
char a[1];
};

struct B
{
char a[1];
double d;
};

void main()
{
struct A Va;
struct B Vb;

printf\("%d", sizeof\(Va\)\);
printf\("%d", sizeof\(Vb\)\);

}

I got the following results for this program:

HP UX
12
12

AIX
16
12

Why this diference ?

The sizeof operator returns the number of bytes required to store an object of type of its operand. When applied to a structure or a union the result is not necessarilly the sum of the size of the members of the union. Padding is also required to make the object tile an array.

Yes, sizeof return the bytes that the struct allocate in memory but how two struct's with the same description, the diference is only in the order of fields, can have diferent sizes?
How a double and a char[] can have a diferent sizeof a char[] and a double. That's my doubt.:confused:

I have to agree that 16 looks like a screwy value. I suspect that the compiler erred as it allocated the structure. This error may be causing it to waste some space in memory. Perhaps you file a bug report to the AIX people.

But remember that the standards to not require a compiler to be efficient. Legal C code will work fine even if this is a bug in the compiler. And it's possible that there is some good reason for this behavior.

It's not an error; the compliler just left some memory between the array and the double. You can check that there is not a problem if instead of array of chars of size 1, as you have in your programme, you put just a char, the size of the structs would be the same in both machines.

I would say that this behavior is probably "normal".
The problem is often encountered with one of element alignment
within structures. Compilers may pad structures with "invisible"
elements to allow each "visible" element to align on a 2- or 4-
byte address boundary. This is done for efficiency in accessing
the element while in memory. Padding may also be added to the
end of the structure to bring it's total length to an even number
of bytes. This is done so the data following the structure in
memory will also align on a proper address boundary.

The behaviour observed is very normal.
It's the system behaviour which will allocate memory to store the structure data.
While doing so, the system will compute the member having highest size and then accordingly will reallocate memory segments for other members of structure.

If you want to avoid this behaviour you can define a structure as a packed structure.
In that case system will allocate memory only as actually required and you can get same result on both the systems.

Also one interesting point to note is the order in which elements are defined in the structure also impact the o/p of sizeof operator

i think it is a big trouble in communication between systems.because the message package is different.