user123 user123 - 3 months ago 17
C Question

Request for member 'next' in something not a structure or union

I am trying to write a function to delete the first node in the linked list, but I am getting the following error:

prog.c: In function 'del':
prog.c:38:13: error: request for member 'next' in something not a structure or union
head=head->next;
^


Any help is highly appreciated. Below is my code:

#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node* next;
};

int length(struct node* head)
{
struct node* current=head;
int count=0;
while(current!=NULL)
{
count++;
current=current->next;

}
return count;
}

void push(struct node** head, int ndata)
{
struct node* new_node=(struct node*) malloc(sizeof(struct node));
new_node->data = ndata;
new_node->next = (*head);
*head=new_node;


}

void del(struct node** head)
{
if(head==NULL)
return;
else
{
struct node *temp=*head;
head=head->next; // Line 38
printf("data del is %d\n", temp->data);
free(temp);
}

}

int main()
{

struct node* head = NULL;

push(&head, 1);
push(&head, 3);
push(&head, 1);
push(&head, 2);
push(&head, 1);

printf("count of nodes is %d", length(head));
del(&head);

return 0;
}

Answer

this line:

head=head->next;

is not correct because head does not point to the first entry in the list,

rather it points to the 'head' pointer, those contents point to the first entry in the list.

So you could possibly use:

*head = (*head)->next;
Comments