为什么我不能动态分配这个结构字符串的内存?

时间:2014-10-11 02:43:50

标签: c struct dynamic-memory-allocation strcpy

比方说,我有一个结构:

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

为什么我不能执行以下操作:

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

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

2 个答案:

答案 0 :(得分:1)

您需要先为human分配空间:

Person *human = malloc(sizeof *human);

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

答案 1 :(得分:0)

您必须为结构Person分配内存。指针应指向为结构分配的内存。只有这样,您才能操纵结构数据字段。

结构Person包含id,char指针name到名称。您通常希望为名称分配内存并将数据复制到其中。 在程序结束时,请记住为namePerson释放内存。 下达订单很重要。

小样本程序来说明这个概念:

#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;
}

输出:

Human= John Smith, with id= 666.