J
James Antill
James said:Mark Bluemel wrote:
...
I think Santosh was suggesting a structure approach like this :-
typedef struct {
short length;
char data[]; /* or "char data[1];" if c99 support isn't
available */
} my_string;
so if you had a string of 32 characters to work with, you'd do
something like:-
my_string *string_pointer = malloc(sizeof(short) + 32);
That assumes there are no padding bytes between length and data. The
right way to calculate the allocation is
#include <stddef.h>
...
mystring *string_pointer = malloc(offsetof(my_string, data) +
32);
This is required to be the same as sizeof(mystring),
Citation, please?
6.7.2.1
#16
As a special case, the last element of a structure with more than
one named member may have an incomplete array type; [...] the
size of the structure shall be equal to the offset of the last
element of an otherwise identical structure that replaces the
flexible array member with an array of unspecified length
#17 even gives an example basically identical to what I posted.