尝试将从函数返回的结构复制到数组内部的结构时出现内存错误

时间:2019-06-07 20:16:17

标签: c

createPerson()返回struct,person是指向person数组的指针 结构指针(personNode **)。试图复制的回报 createPerson()到personNode [x],内存错误。

people[length - 1]->age = createPerson(name, age)->age;
strcpy(people[length - 1]->name, createPerson(name, age)->name);
typedef struct personNode
{
    char name[20];
    int age;
    struct personNode* next;
}personNode;

personNode* createPerson(char name[], int age)
{
    personNode* person = (personNode*)malloc(sizeof(personNode));

    strcpy(person->name, name);
    person->age = age;

    return person;
}

  void addPerson(personNode** people, int length)
{
int i = 0;
    int age = 0;
    char* name = 0;

    people = (personNode**)realloc(people, sizeof(personNode*) * length + 1);
    name = (char*)realloc(name, 20);
    printf("Enter name: ");
    fgets(name, 20, stdin);
    name[strcspn(name, "\n")] = 0;
    printf("Enter age: ");
    scanf("%d", &age);
    getchar();
    people[length - 1]->age = createPerson(name, age)->age;
    strcpy(people[length - 1]->name, createPerson(name, age)->name);

预期不会崩溃,崩溃了。

0 个答案:

没有答案