在链接列表中添加节点

时间:2014-03-25 21:40:33

标签: c struct linked-list nodes

我正在尝试将用户添加到链接列表中。我有两个结构和一个添加名为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;
}

2 个答案:

答案 0 :(得分:2)

代码不比较字符串。它会将char - 圈子与UserAccountNode* friend_list进行比较。但stricmp要求两个参数都为const char *。您必须循环浏览friend_list中的所有项目,并将每个username与给定项目进行比较。

另一个问题:您为UserAccountNode分配内存,但不为其内部字段UserAccount* content分配内存。当您尝试读取数据时,它可能会使应用程序崩溃。

答案 1 :(得分:2)

Circle的类型为char而非char*head->friend_list的类型为UserAccountNode*

因此,您尝试将非字符串对象比较为字符串:

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

我认为你的程序无法编译。

相关问题