我在使用主程序中 make_employee 函数返回的指针时遇到问题。
//我在单独的 .c 文件中有以下代码:
struct Employee;
struct Employee* make_employee(char* name, int birth_year, int start_year){
struct Employee* new = (struct Employee*)malloc(sizeof(struct Employee));
strcpy(new->name, name);
new->birth_year = birth_year;
new->start_year = start_year;
return new;
}
//In the main program:
int main()
{
char test_name[] = "Fred";
int test_birth = 1989;
int test_start = 2007;
Employee Fred;
make_employee(test_name, test_birth, test_start) = &Fred; <-- throws invalid lvalue error
return 0
}
最佳答案
你不能给非左值赋值。因此名称(左值,左侧值,可以出现在赋值表达式的左侧 侧)。
这是你想要做的吗??
int main()
{
char test_name[] = "Fred";
int test_birth = 1989;
int test_start = 2007;
struct Employee *fred = make_employee(test_name, test_birth, test_start)
// use fred....
free(fred);
return 0
}
注意:不要在 C 中转换 malloc()
。确保 stdlib.h
包含在您的源文件中,如果您忘记了,让编译器警告您这样做。如果您收到一条警告,说明“malloc
的隐式声明返回 int
”等,这意味着您忘记包含 stdlib.h
,你应该这样做。
关于c - 将指向结构的指针分配给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14720194/