Hi!
I just stated reading "algorithms in C" by robert sedgewick. I wrote a couple of simple programs to create linked list but each one gave me some problems The problems I have are highlighted in bold. Here is the first simple program:
why do i get and error when i run the above program ?Code:#include<stdio.h> #include<stdlib.h> struct node { int item; struct node *next; } *start; int main() { int i, N = 4; struct node *x; start = x; for(i = 1; i <= N; i++) { x->next = (struct node*) malloc(sizeof(struct node)); x = x->next; x->item = N-i+1; if(i == N) { x->next = NULL; break; } else x = x->next; } return 0; }![]()
Here is second program:
This program complies and links fine but does not print the list as i expected ????Code:#include<stdio.h> #include<stdlib.h> typedef struct node *link; struct node { int item; link next; }; void printlist(link t1) { while(t1 != NULL) { printf("%d, ", t1->item); t1 = t1->next; } } int main() { int i, N = 5; link x, t; t = x; for(i = 1; i <= N; i++) { x = malloc(sizeof(link)); if(1 == i) t = x; x->item = i; if(i == N) x->next = NULL; x = x->next; } printlist(t); return 0; }![]()
Also the book uses the malloc function in a different way which I didn't really understand
x->next = malloc(sizeof *x)
I don't understand what is going on in this malloc the sizeof operator (takes a pointer to x ????) and there is no typecasting in the return ??![]()
I am a little flimsy on my basics I guess , any help would be great
I used devC++ compiler to compile these.



LinkBack URL
About LinkBacks



