c - 将指向结构的指针分配给变量

标签 c pointers struct variable-assignment lvalue

我在使用主程序中 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/

相关文章:

c - 我不明白为什么我不能像这样在末尾添加节点

c++ - 如何使用智能指针围绕 C 'objects' 实现包装器?

C 全局匿名结构/union

c - undefined reference 'WinMain@16' C 错误

c - 关于 C 代码和 Pollard 对数 rho 算法的问题

c - BST 中的段错误

c - 在没有赋值的情况下初始化结构?

c - 链接列表无法正常工作

c++ - 使用指针进行选择排序

c - 编写一个函数来测试点是否在矩形中