If I have a struct defined as such:
typedef struct{
char a[];
}my_struct_t;
How do you allocate memory for a string with malloc() such that it is stored in my_struct_t?
Code could use a flexible array member FAM to the store string in the structure. Available since C99. It requires at least one more member in the struct than OP's code.
As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member. ... C11 §6.7.2. 18
typedef struct fam {
size_t sz; // At least 1 member.
char a[]; // flexible array member - must be last.
} my_struct_t;
#include <stdlib.h>
#include <string.h>
my_struct_t *foo(const char *src) {
size_t sz = strlen(src) + 1;
// Allocate enough space for *st and the string.
// `sizeof *st` does not count the flexible array member.
struct fam *st = malloc(sizeof *st + sz);
assert(st);
st->sz = sz;
memcpy(st->a, src, sz);
return st;
}
As exactly coded, the below is not valid C syntax. Of course various compilers offer language extensions.
typedef struct{
char a[];
}my_struct_t;
char a[1]; so the technique has been used for decades. That older technique had issues that are satisfied with C99 and char a[]; ( alignment, sizeof struct, analysis tools). Like many tools in the C shed: use the right tool for the right job.malloc(sizeof *st + sizeof *(st->a) * N); idiom is used when the last array element is not char [].#include <stdio.h>
#include <stdlib.h>
typedef struct {
char* a;
} my_struct_t;
int main()
{
my_struct_t* s = malloc(sizeof(my_struct_t));
s->a = malloc(100);
// Rest of Code
free(s->a);
free(s);
return 0;
}
Array of 100 chars.
my_struct_t?" . This answer likely meets OP's goal, yet it does not store the string in the structure, but stores a pointer to the future string.
char *with a funny type.