在c中按函数填充typedef结构

时间:2017-01-28 15:32:17

标签: c struct malloc typedef dynamic-memory-allocation

我想按功能填充typedef结构。我试过了:

typedef struct{
    char *first_name, *last_name;
    int id;
    Date birthday;
} Person;

void ReadPerson(Person* person){
    person = (Person*)malloc(sizeof(Person));
    person->first_name = readString();
    person->last_name = readString();
    scanf("%d",&(person->id));
    ReadDate(&(person->birthday));
}

主要功能:

void main(){
    Person *tmp = NULL;
    ReadPerson(tmp);
}

使用Bad Ptr值调用ReadPerson tmp后。

1 个答案:

答案 0 :(得分:0)

如果在定义时在同一代码段中对变量进行malloc操作,可能会更优雅。如果您要定义" Person * tmp"将信息存储在main()中,然后在main()中使用malloc。在ReadPerson()上删除malloc。

相关问题