1
我有這樣的代碼:ç引用傳遞(指針)崩潰
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct employee {
char *name;
double salary;
} employee;
void new_employee (employee *person, char *name, double salary) {
person = malloc(sizeof(employee));
person->name = malloc(strlen(name) + 1);
strcpy(person->name, name);
person->salary = salary;
printf("Employee: name=%s salary=%f\n", person->name, person->salary);
}
int main(int argc, char *argv[])
{
employee *bob = 0;
new_employee(bob, "Bob Doe", 1000);
printf("Employee: name=%s salary=%f\n", bob->name, bob->salary);
return 0;
}
我不知道什麼是錯的,但我可以在new_employee使用結構,但是當我嘗試使用它它打破從主要。基本上第一個printf工作在第二個崩潰。我認爲主要是沒有得到鮑勃更新,但我使用了一個指針,所以它應該通過引用。
改變你的new_employee函數返回的人,即員工'* new_employee(...){...回報的人; }' –