Can I safely cast the struct a to char* safely?
The cast itself is safe. Accessing the contents of the pointer *(pChar+2) = 27;
is not safe. Formally it may invoke undefined behavior because it violates aliasing.
(Using char* is fine as far as the aliasing rules are concerned, but when writing the value 27 to a random byte, there are formally no guarantees of what the result will be. And you might be writing to a padding byte.)
And will the padding be added to the end of the struct?
Padding may be added anywhere in the struct, except at the very beginning.
In practice, doing things like this is likely rather safe, even though it is not recommended and formally undefined behavior. I have yet to encounter a system where it wouldn't work safely and deterministically. But you have to ensure that there is no padding:
struct Numbers {
short CharCount;
char FirstChar;
char SecondChar;
char ThirdChar;
};
static_assert(sizeof(struct Numbers) ==
sizeof(short) +
sizeof(char) +
sizeof(char) +
sizeof(char),
"Padding found");
To actually disable padding there is usually some non-standard way such as #pragma pack(1)
.
EDIT
The best and most portable way to reliably get the address of a struct member might be this:
#include <stddef.h>
struct Numbers x;
char* ptr = (char*)&x + offsetof(struct Numbers, FirstChar);