简体   繁体   中英

Why can't I dynamically allocate memory of this string of a struct?

Let's say for example, I have a struct:

typedef struct person {
    int id;
    char *name;
} Person;

Why can't I do the following:

void function(const char *new_name) {
    Person *human;

    human->name = malloc(strlen(new_name) + 1);
}

You need to allocate space for human first:

Person *human = malloc(sizeof *human);

human->name = malloc(strlen(new_name) + 1);
strcpy(human->name, new_name);

You have to allocate memory for the structure Person . The pointer should point to the memory allocated for the structure. Only then you can manipulate the structure data fields.

The structure Person holds id, and the char pointer name to the name. You typically want to allocate memory for the name and copy the data into it. At the end of the program remember to release memory for the name and the Person . Release order is important.

Small sample program to illustrate the concept is presented:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct person {
    int id;
    char *name;
} Person;


Person * create_human(const char *new_name, int id) 
{
    Person *human = malloc(sizeof(Person));       // memory for the  human

    human->name = malloc(strlen(new_name) + 1);   // memory for the string
    strcpy(human->name, new_name);                // copy the name

    human->id = id;                               // assign the id 

    return human; 
}

int main()
{
    Person *human = create_human("John Smith", 666);

    printf("Human= %s, with id= %d.\n", human->name, human->id);

    // Do not forget to free his name and human 
    free(human->name);
    free(human);

    return 0;
}

Output:

Human= John Smith, with id= 666.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM