user3315144
user3315144

Reputation: 33

Adding Nodes in Linked List

I am trying to add users to a linked list. I have two structs and a method to add called add_friend that sets up the addition of the node. The program does not ask for user input but passes the info through parameters in the add_friend method: In addition to adding the node (user) to the list I have to check if user already exists. I am getting an error when I try to compare string to see if the user exists. Any help? Unfortunately C is my weakest programming language, Im having a hard time understanding the pointers

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;
}

Upvotes: 0

Views: 165

Answers (2)

Sandro
Sandro

Reputation: 2786

type of Circle is char not char*, type of head->friend_list is UserAccountNode*.

So, you try to compare non-string objects as strings here:

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

I think your program can't be compiled.

Upvotes: 2

VladimirM
VladimirM

Reputation: 817

The code does not compare strings. It compares char - Circle - with UserAccountNode* friend_list. But stricmp requires both arguments to be const char *. You have to do a loop through all items in friend_list and compare every username with a given one.

Another issue: you allocate memory for UserAccountNode but do not allocate memory for its internal field UserAccount* content. It may crash the application when you try to read the data.

Upvotes: 2

Related Questions