> Padding still scares me though.
There is nothing scary about the 'contiguous sequence of characters' (that the C standard talks about).
1. A char has no alignment requirements; no padding is added in a struct where every member is a char. Padding applies only when types having alignment requirements greater than one are involved.
2. Therefore, the strict aliasing rules of both C and C++ allow any object to be inspected as a sequence of contiguous bytes; a pointer to any object can be safely used/cast as a pointer to const char (Hence
std::memcpy()
,
std::ostream::write()
etc.)
struct B
is only a little bit more involved; it relies on this specification in the C standard: within a struct, members ( C++ adds 'with the same access control') declared later have higher addresses than members declared earlier.
So the layout of
1 2 3 4 5
|
struct B
{
int sz ;
char name[DYNAMICALLY_SIZED] ;
};
|
is: the sz member at an offset of zero, the single char in name after that.
If we allocate more memory, as in
malloc( sizeof( struct B ) + strlen(name) )
, the sequence of bytes starting with the single character in name up to the end of the allocation is a contiguous sequence of chars. And if we put a null character in one of those bytes, we have a C-style string:
a contiguous sequence of characters terminated by and including the first null character.
And after
strcpy( pb->name, name )
,
pb->name
is a C-style string.
> "Structures are not string. They can be casted to strings" - vlad from moscow
A C-style string is not a type; it is a concept. Till you understand that, you will continue to have these kinds of problems.