typedef struct {
char *somechar;
} Random;
Requires first to allocate the struct itself:
Random *r = malloc(sizeof(*r));
and then an array somechar
has to point to. Without this, it will be uninitialized, invoking undefined behaviour if you dereference it.
r->somechar = malloc(MAX_ARRAY_LENGTH);
MAX_ARRAY_LENGTH
has to be set to the max. number of entries you want to store into that char
array. As sizeof(char)
is defined 1
by the standard, no need to specify this explicitly.
Note that you should not cast void *
as returned by malloc
& friends. Whoever tells you should read here.
Caution:
- Always check the result of system functions.
malloc
can fail, returning a null pointer. Dereferencing such is undefined behaviour and can make your program crash - if you are lucky (if not, you will not notice anything, but get strange behaviour - like nasal demons).
- If you want to store a C-string in that
char
array, account for the trailing '\'
- Note that all
malloc
ed memory is uninitialized. If you want zeroed memory, use calloc
.
free
both allocated blocks! Use the reverse order of allocation.
If using C99 or C11 (recent standard), you can use a flexible array member and avoid the second allocation:
typedef struct {
char somechar[]; // must be last member of the struct
} Random;
...
Random *r = malloc(sizeof(*r) + MAX_ARRAY_LENGTH);
This will allocate the struct with the array of the given size in a single block.