I want to be create a struct, but I also want to write its array or string elements with dynamic memory allocation.
struct st {
char *name[40];
int age;
};
For "name" string should I use malloc before struct, or can I use it in struct also.
1)
char *name = malloc(sizeof(char)*40);
struct st {
char *name;
int age;
};
2)
struct st {
char *name = malloc(sizeof(char)*40);
int age;
};
Are both of them true or is there any mistake? And if both of them are true, which one is more useful for other parts of code?
char, i.e. an array of 40 strings. The second structure (alternative 1) will just have single pointer, who is totally unrelated to thenamevariable you define before the structure. The third structure (alternative 2) will not compile.namemember? Also, allocating memory for thenamemember dynamically with a compile-time constant fixed size make no sense, just use an array.