Different data types have different alignment requirements. Most of the time, these alignment requirements are dictated by the architecture the program is run on, however, the compiler could conceivably have some extra functionality that enabled the effect of unaligned accesses, by, for instance, making multiple reads/writes and assembling the parts itself. On some platforms, like x86, unaligned accesses are slower than aligned accesses, but they work. On other systems, it makes the program crash. So, naturally, the compiler would want to lay out the members in a struct so that when they were accessed, the accesses would be aligned.Originally Posted by N1256 3.2#1
In the case of your struct, it's likely that an int is 4 bytes and is aligned to a 4-byte boundary. The char would be 1 byte and aligned to a 1-byte boundary. Thus, the char can be located at any byte address, but aligned ints can only begin at every 4 byte addresses.
The compiler has to account for the possibility of the struct being an element of an array. Since arrays have to be contiguous, the compiler has to add padding somewhere in the struct in order for array[1] and later elements' int member to be properly aligned. This means an extra 3 bytes of padding. This could be inserted either betwen the int and char members, or the char member and the end, but not before the first member. This explains why the struct has size 8.Putting a struct in a union with a char array would typically do nothing to affect alignment.The extra 3 bytes is not assigned to the char, but to the struct in the form of padding.sizeof returns type size_t, which is an unsigned integer type. %d is for signed int. If you are using C89, the closest you can get to a correct format specification is to use %lu and cast the argument to unsigned long. In C99, there is the format specification %zu. Subtracting two pointers results in a ptrdiff_t, not a signed int, as your format specification suggests. The correct format specification would be %td. However, the expressions that evaluate to the ptrdiff_t types invoke undefined behavior because 'pointer - pointer' is only defined when both pointers point to the same array object.Depending on the objective, assembler might make it easier for the person to accomplish his/her task, and therefore be easier.