Allocation of memory for char array

前端 未结 10 849
孤独总比滥情好
孤独总比滥情好 2021-01-02 12:45

Let\'s say you have-

struct Person {
    char *name;
    int age;
    int height;
    int weight; 
 };

If you do-

struct Pe         


        
10条回答
  •  猫巷女王i
    2021-01-02 13:20

    It won't know, You will have to allocate memory for it separately.

    struct Person *who = malloc(sizeof(struct Person));
    

    Allocates enough memory to store an object of the type Person.
    Inside an Person object the member name just occupies a space equivalent to size of an pointer to char.
    The above malloc just allocates that much space, to be able to do anything meaningful with the member pointer you will have to allocate memory to it separately.

    #define MAX_NAME 124
    who->name = malloc(sizeof(char) * MAX_NAME);
    

    Now the member name points to an dynamic memory of size 124 byte on the heap and it can be used further.

    Also, after your usage is done you will need to remember to free it explicitly or you will end up with a memory leak.

    free(who->name);
    free(who); 
    

提交回复
热议问题