In my project we have a piece of code like this:
// raw data consists of 4 ints
unsigned char data[16];
int i1, i2, i3, i4;
i1 = *((int*)data);
i2 = *((int*
Whether you have to worry about alignment depends on the alignment of the object from which the pointer originated.
If you cast to a type which has stricter alignment requirements, it is not portable.
The base of a char array, like in your example, is not required to have any stricter alignment than that for the element type char.
However, a pointer to any object type can be converted to a char * and back, regardless of alignment. The char * pointer preserves the stronger alignment of the original.
You can use a union to create a char array which is more strongly aligned:
union u {
long dummy; /* not used */
char a[sizeof(long)];
};
All the member of a union start at the same address: there is no padding at the beginning. When a union object is defined in storage, it must therefore have an alignment which is suitable for the most strictly aligned member.
Our union u above is aligned strictly enough for objects of type long.
Violating the alignment restrictions can cause the program to crash when it is ported to some architectures. Or it may work, but with mild to severe performance impact, depending on whether misaligned memory accesses are implemented in hardware (at the cost of some extra cycles) or in software (traps to the kernel, where software emulates the access, at a cost of many cycles).