Reputation: 7
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);
}
Upvotes: 0
Views: 90
Reputation: 1102
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.
Upvotes: 1
Reputation: 13
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.
Upvotes: 0
Reputation: 54
I don't think changing head from pointer to pointer (**) to a pointer will work. Passing the address of head from main should work.
Upvotes: 0