I need help with the following code about linked lists:
#include <stdlib.h>
#include <stdio.h>
struct nodo {
int d;
struct nodo *next;
};
struct nodo *full();
int main()
{
struct nodo *l;
/* l=(struct nodo *)malloc(sizeof(struct nodo)); */
l = full();
while(l!=NULL) {
printf("-->%d\n", l->d);
l =l->next;
}
system("PAUSE");
}
struct nodo *full()
{
int i;
struct nodo *head, *nes;
head = (struct nodo *)malloc(sizeof(struct nodo));
head->next = NULL;
for(i = 1; i < 5; i++) {
nes = (struct nodo *)malloc(sizeof(struct nodo));
printf("Insert the %d element:\n", i);
scanf("%d", &nes->d);
nes->next = head;
head = nes;
}
return head;
}
If I try for example to input 1, 2, 3, 4, I get the following output:
-->4
-->3
-->2
-->1
-->9708864
Why do I get the last number? What’s wrong with my code?
As @Vinska pointed out in the comments, line 3 of
full()is not necessary; it is creating an extra node.The line in question is
head = (struct nodo *)malloc(sizeof(struct nodo));Instead, say
head = NULLWith your existing code, your linked list has 5 elements. The first one is created on the aforementioned line. The remaining four items are created in the loop, as expected, for a total of 5 elements.
The
9708864number is a garbage value. It is whatever happened to be in memory when you calledmalloc(). This is why you have to initialize all of your variables! Or, in this case, usememset()orcalloc()to set those blocks to some sane value. (However, that line is completely superfluous here anyway.)Good luck!