Reputation: 420
I made this code,following the functions given in the book "Fundamental Of Data Structures in C",I made the following code for implementing a simple linked list,but I don't seem to get where I am wrong,as the book code is supposed to be correct:
#include<stdio.h>
#include<stdlib.h>
typedef struct node *listpointer;
typedef struct {
int data;
listpointer link;
} node;
void print(listpointer first)
{
while (first) {
printf("%d\n",first->data);
first=first->link;
}
}
void addAtFront(listpointer *first,int n)
{
listpointer t=*first,temp;
temp=malloc(sizeof(node));
int i=1;
while (i <= n) {
t=t->link;
i++;
}
if(*first) {
temp->link=t->link;
temp->data=90;
t->link=temp;
}
else
{
*first=temp;
temp->link=NULL;
}
}
listpointer createList( )
{
listpointer first,second;
if(first=malloc(sizeof(node))) {
first->data=67;
if(second=malloc(sizeof(node))) {
second->data=65;
first->link=second;
second->link=NULL;
}
}
return first;
}
main( )
{
listpointer first=createList( );
addAtFront(&first,2);
print(first);
}
Upvotes: 2
Views: 4213
Reputation: 1
Why I was getting this error was because I had not included the header file which contained the structure definition.
Upvotes: 0
Reputation: 224944
You have this typedef:
typedef struct node *listpointer;
But you didn't ever define struct node
. You have this definition of an anonymous struct
typedef
ed to node
, though:
typedef struct {
int data;
listpointer link;
} node;
Probably you meant:
typedef struct node {
int data;
listpointer link;
} node;
Upvotes: 6
Reputation: 183888
You define the struct without a tag,
typedef struct node *listpointer;
typedef struct {
int data;
listpointer link;
} node;
so the struct node
that a listpointer
is supposed to point to remains an incomplete type.
You should give the struct a tag,
typedef struct node { ...
then listpointer
points to a complete object type.
Upvotes: 5