C语言 添加链表节点



我正在尝试将用户添加到链表。我有两个结构体和一个名为add_friend的方法,用于设置节点的添加。程序不要求用户输入,而是通过add_friend方法中的参数传递信息:除了将节点(user)添加到列表中之外,我还必须检查user是否已经存在。当我尝试比较字符串以查看用户是否存在时,我得到了一个错误。任何帮助吗?不幸的是,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;
}

代码不比较字符串。对char - Circle和UserAccountNode* - friend_list进行了比较。但是stricmp要求两个论点都是const char *。你必须对friend_list中的所有项目进行循环,并将每个username与给定的项目进行比较。

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

Circle的类型是char不是char*head->friend_list的类型是UserAccountNode* .

那么,你试着将非字符串对象与字符串进行比较:

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

我认为你的程序无法编译

最新更新