我在此实施中遇到了许多错误。
typedef struct EmployeeStruct
{
char lastName[MAX_LENGTH];
char firstName[MAX_LENGTH];
int employeeNumber; // Holds the employee's ID. This value is
// equal to the number of employees
struct EmployeeStruct *Next; // Pointer to the next most recently hired Employee
}Employee;
当尝试创建一个将返回指向此结构的指针的函数时,会出现问题。错误来自malloc电话,并导致" new"未被正确声明,因此此函数中的所有行都有错误。
Employee* hireEmployee(Employee tail, char lastName[MAX_LENGTH], char firstName[MAX_LENGTH])
{
struct Employee *new = (Employee*)malloc(sizeof(Employee));
new.lastName = lastName;
new.firstName = firstName;
new.next = tail;
tail.next = new;
new.employeeNumber = employeeCount;
return tail;
}
以下是错误列表。谢谢你的帮助!
lab6.c:19: warning: initialization from incompatible pointer type
lab6.c:20: error: request for member ‘lastName’ in something not a structure or union
lab6.c:21: error: request for member ‘firstName’ in something not a structure or union
lab6.c:22: error: request for member ‘next’ in something not a structure or union
lab6.c:23: error: ‘Employee’ has no member named ‘next’
lab6.c:24: error: request for member ‘employeeNumber’ in something not a structure or union
lab6.c:26: error: incompatible types in return
答案 0 :(得分:4)
这里有一些不同的问题:
您需要使用指针取消引用运算符->
来访问指向结构的指针的成员。
然后,您需要使用strcpy分配给char
数组。
您需要避免链接列表中的循环(您将new
和tail
设置为彼此指向next
)。明显的解决方法是将new
设置为新的tail
。可能需要更新调用代码以反映这一点。
最后,你不应该从malloc
投出回报
最后,next
应为Next
。或者您可以在结构定义中更改大小写。
Employee *new = malloc(sizeof(Employee));
strcpy(new->lastName, lastName);
strcpy(new->firstName, firstName);
new->Next = NULL;
tail->Next = new;
new->employeeNumber = employeeCount;
答案 1 :(得分:0)
这里有几件事
1)Employee已经是typedef,所以不需要在malloc语句中使用struct
2)new是指向struct的指针。因此,通过指针访问struct对象的方法是StructPointer-> StructObject或*(StructPointer).StructObject
3)我看到你正在尝试将tail分配给next但是将tail作为struct对象传递。它必须是一个StructPointer。
4)你应该使用strcpy来复制字符数组。