将结构的指针分配给变量

时间:2013-02-06 01:38:29

标签: 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
}

2 个答案:

答案 0 :(得分:2)

您无法将内容分配给非左值。因此,名称(l值,左侧值,可以出现在赋值表达式的左侧侧)。

这个你想要做什么?

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,并且您应该这样做。

答案 1 :(得分:0)

我认为你需要检查你的make_employee函数。我这么说的原因是你发布的代码使用了以下行

struct Employee* new = (struct Employee*)malloc(sizeof(struct Employee));

new是C ++中的关键字,如果您使用过C ++编译器,它应该立即抛出编译错误。将关键字用作变量名称是不好的。

还要检查函数的返回值。

假设你已正确宣布你的结构,这应该可以正常使用

struct Employee* make_employee(char* name, int birth_year, int start_year){
  struct Employee *ptr = (struct Employee*)malloc(sizeof(struct Employee));
  strcpy(ptr->name, name);
  ptr->birth_year = birth_year;
  ptr->start_year = start_year;
  return ptr;
}


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

  printf("Printing the data contents");
  printf("\n Name : %s",Fred->name);
  printf("\n Birth : %d",Fred->birth_year);
  printf("\n Start :%d",Fred->start_year);
  free(Fred);
  return 0;
}