2014-03-25 142 views
0

我正在嘗試將用戶添加到鏈接列表中。我有兩個結構和一個方法來添加名爲add_friend的設置節點的添加。程序不要求用戶輸入,而是通過add_friend方法中的參數傳遞信息:除了將節點(用戶)添加到列表中,我必須檢查用戶是否已經存在。當我嘗試比較字符串以查看用戶是否存在時,出現錯誤。任何幫助?不幸的是C是我最弱的編程語言,我很難理解指針在鏈接列表中添加節點

struct UserAccountNode{ 

struct UserAccount* content; 
char circle; 
struct UserAccountNode* next; 

    }*head = NULL ; 

    struct UserAccount{ 

char username[255]; 
char lastnm [256]; 
char firstnm[256]; 
char password[256]; 
char gender; 
int phone; 
struct Post* post_list; 
struct UserAccountNode* friend_list; 
    } ; 

int add_friend(UserAccount* user, char Circle, UserAccount* Friend) 
{ 
struct UserAccountNode* friend_list; 

friend_list = (struct UserAccountNode*) malloc (sizeof(struct UserAccountNode)); 

while (friend_list != NULL) 
    if (stricmp(Circle, head->friend_list) == 0) 
    { 
     friend_list -> next = head; 
     head = friend_list; 
    } 

    else{ 

     printf("%d, User Already Exists", Friend); 

     } 

return 0; 
} 
+1

如果這是[的解剖**這**](http://stackoverflow.com/questions/22627293/adding-a-new-user-to-list-in-c-program)的後果,你需要放下StackOverflow並拿起你的課本。認真。 *停止編寫代碼,花一些時間研究和閱讀它。*沒有捷徑。 – WhozCraig

+0

你想如何確定朋友是否已經在列表中?你能否檢查一個具有相同地址的用戶是否已經存在? – pat

回答

1

代碼不會比較字符串。它將char - Circle - 與UserAccountNode* friend_list進行比較。但是stricmp需要兩個參數爲const char *。您必須對friend_list中的所有項目進行循環,並將每個username與給定的項目進行比較。

另一個問題:您爲UserAccountNode分配內存,但不爲其內部字段UserAccount* content分配內存。當您嘗試讀取數據時,它可能會使應用程序崩潰。

1

類型的Circlecharchar*, 類型的head->friend_listUserAccountNode*

所以,你嘗試非String對象這裏比較作爲字符串:

if (stricmp(Circle, head->friend_list) == 0)

我覺得你的程序不能編譯。