Allocation of memory for char array

前端 未结 10 712
孤独总比滥情好
孤独总比滥情好 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:25

    It allocates memory for the just the pointer to a char. You need to do a separate allocation for the contents.

    There are other options although:

    If you are OK with having a fixed sized maximum length, you can do:

    struct Person {
        char name[PERSON_NAME_MAX_LENGTH+1];
        int age;
        int height;
        int weight; 
     };
    

    And allocate it as in your example.

    Or you can declare a variable sized struct, but I wouldn't recommend this as it is tricky and you cannot have more than one variable size array per struct:

    struct Person {
        int age;
        int height;
        int weight; 
        char name[]; /*this must go at the end*/
     };
    

    and then allocate it like:

    struct Person *who = malloc(sizeof(struct Person) + sizeof(char)*(name_length+1));
    

提交回复
热议问题