Search code examples
cstructuredynamic-memory-allocation

Dynamic memory allocation for arrays and strings in struct in C


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?


Solution

  • You need to create an instance of the structure, an actual variable of it. Then you need to initialize the members of the structure instance in a function.

    For example, in some function you could do

    struct st instance;
    instance.name = malloc(...);  // Or use strdup if you have a string ready
    instance.age = ...;