Allocation of memory for char array

前端 未结 10 824
孤独总比滥情好
孤独总比滥情好 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条回答
  •  天涯浪人
    2021-01-02 13:33

    For pointers the struct is allocated enough memory just for the pointer. You have to create the memory for the char* and assign the value to the struct. Assuming you had char* name somewhere:

    struct Person *who = malloc(sizeof(struct Person));
    who->name = malloc((strlen(name)+1) * sizeof(char));
    strcpy(who->name, name)
    

提交回复
热议问题