Frage

Program compiles but when I create list and try to display it I don't get same thing as I inputted so I guess there's something wrong with my code. So if somebody could point where its wrong and possibly correct it that would be great:

struct client
{
    char name[30];
    struct client *next;
};

struct client* FindTailClient(struct client* head)
{
    while( head->next != NULL)
    {

        head = head->next;
    }
    return head;
}

struct client* AddClient(struct client** head, char name[])
{
    struct client* newnode =malloc(sizeof(struct client));
    if (newnode == NULL) {
        fprintf(stderr, "failed to allocate memory.\n");
        return -1;
    }
    newnode->next = NULL;
    strcpy(newnode->name,name);
    if(*head == NULL)
    {
        *head = newnode;
    }
    else
    {
        struct client* node = FindTailClient(*head);
        node->next = newnode;
    }
}

void Display(struct client *head)
{
    struct client *current = head;
    while (current != NULL)
    {
        printf("%s",current->name);
        current = current->next;
    }
}

int main()
{
    int i;
    struct client *head ;


    char name[30];
    for (i = 0; i < 5; i++)
    {
        scanf("%s",name);
        AddClient(head,name);
    }
    Display(head);
}
War es hilfreich?

Lösung

In AddClient() you are declaring struct client **head, but you are passing a struct client * to it.

Get rid of the extra asterisk (change ** to * and change *head to head in AddClient) and it should work. Or, pass &head to AddClient(), although I can't see any reason to have a pointer to a pointer to the head of your list.

Andere Tipps

I don't think changing head from pointer to pointer (**) to a pointer will work. Passing the address of head from main should work.

in find client don't make the head node point to null create a temp node and male it point toward null. like this

struct client *find_client(struct client *head) {
    struct client *temp = head;

    while (temp->next != NULL) {
        temp =temp->next;    
    }

    return temp;
}

we don't have to make the head go to the end just we have to go to the end.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top