简体   繁体   English

用C中的函数填充typedef结构

[英]Fill typedef struct by function in c

I want to fill typedef struct by function. 我想按功能填充typedef结构。 I tried: 我试过了:

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

the main function: 主要功能:

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

After calling ReadPerson tmp with Bad Ptr value. 用错误的Ptr值调用ReadPerson tmp之后。

Maybe it will be more elegant if you malloc a variable in the same code segment when it is defined. 如果在定义变量时在同一代码段中分配变量,可能会更优雅。 If you are defining "Person *tmp" to store the info in main(), then also use malloc in main(). 如果要定义“ Person * tmp”以将信息存储在main()中,则还应在main()中使用malloc。 Delete malloc on ReadPerson(). 删除ReadPerson()上的malloc。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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