2013-10-25 108 views
0

我遇到了这个实现的一系列错误。使用结构的C函数,为什么它不起作用?

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 
+1

即使你用C编写,使用一些流行的C++关键字,比如'new'也有点混乱。 – ouah

+0

啊,真的。甚至没有想到这一点。好点谢谢 – AKon

+0

你正在使用'next',但是定义了'Next'。你不声明'employeeCount'。你不是取消引用你的指针:使用'new-> Next'代替'new.next'。对于初学者。哦 - 你需要返回地址(因为你的函数的类型是Employee *'),而不是结构本身。 '返回&tail;' – Floris

回答

4

有几个不同的问题在这里:

您需要使用指针引用操作->访问指针成员的结构。
然后您需要使用strcpy分配给您的char阵列。
您需要避免链接列表中的循环(您正在设置newtail以指向对方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; 
+0

我得到这个错误“取消引用指向不完整类型的指针” – AKon

+0

哪一行会给你那个错误?你在编译你的代码,我的建议还是其他的东西?还请注意,我已经更新了我的答案,以解决代码的另一个问题。 – simonc

+0

是的,我改变了struc定义中的名字,是我愚蠢的错误。但是使用你的代码来取消引用指针,我会遇到错误。具体来说,它在函数中使用的每一行。思考? – AKon

0

这里有几件事。
1)Employee已经是typedef,所以不需要在malloc语句中使用struct。
2)new是一个指向struct的指针。所以,通过指针访问结构对象的方法是StructPointer-> StructObject或*(StructPointer).StructObject
3)我看到你正在尝试将tail指定为next,但将tail作为结构对象传递。它必须是一个StructPointer。 4)你应该使用strcpy来复制字符数组。

相关问题