Reputation: 11363
After taking the summer off from C programming, I'm back in the thick of it for classes and am trying to catch up, particularly in pointers.
The current assignment has us converting a program from an array structure to a simple linked list. In order to refresh my memory, I've tried implementing it in a standalone program, but am running into trouble.
My code:
struct node{
int val;
struct node *next;
};
typedef struct node *item;
item newNode(void); //function prototype
void main(){
item *cur, *itemList;
int i;
itemList=NULL;
for (i=0; i<=10; i++){
cur= newNode();
cur->val=i;
cur->next= itemList;
}
}
item newNode(void) {
item box; /* the new object to return */
box = (item) malloc (sizeof (struct node));
if (box == NULL) {
printf("ERROR: emalloc failed for new Box\n");
exit(0);
}
/* initialize fields */
box->val=0;
return box;
}
The first error message is coming at cur= newBox()
and is stating that an assigment from an incompatible pointer type is being made. I'm not sure why, since cur is a pointer to a node, and box is a structure. Where does the incompatible pointer come from?
Upvotes: 2
Views: 1560
Reputation: 34615
cur
is of type item*
, pointer to item. But the return type of newNode(void)
is item
. They both are not type compatible.
Upvotes: 0
Reputation: 70513
You need a pointer
It is clearer if your typedef is like this:
typedef struct node item;
then:
item *newNode(void) {
item *box; /* the new object to return */
box = (item) malloc (sizeof (struct node));
if (box == NULL) {
printf("ERROR: emalloc failed for new Box\n");
exit(0);
}
/* initialize fields */
box->val=0;
return box;
}
Also you call the function newNode and newBox in different places.
You also need to reset the head pointer:
for (i=0; i<=10; i++){
cur= newBox();
cur->val=i;
cur->next= itemList;
itemList = cur;
}
Upvotes: 3
Reputation: 75130
The first problem is that your doing item *cur, *itemList;
which is a node**
. Change that to item cur, itemList;
to get node*
's; you don't need a pointer to a pointer to a node
, just a pointer to a node
.
Another problem is that you're setting all the next
pointers of your nodes to itemList
without setting itemList
to cur
at the end of each loop iteration (which will make itemList
point to the beginning of the list at the end of the loop).
Upvotes: 4
Reputation: 31559
In main you are using item*
which is node**
. Just remove the *
in the declaration list in main.
Upvotes: 1