2013-10-25 114 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來複制字符數組。

相關問題