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?
The first problem is that your doing
item *cur, *itemList;which is anode**. Change that toitem cur, itemList;to getnode*‘s; you don’t need a pointer to a pointer to anode, just a pointer to anode.Another problem is that you’re setting all the
nextpointers of your nodes toitemListwithout settingitemListtocurat the end of each loop iteration (which will makeitemListpoint to the beginning of the list at the end of the loop).