Singly Linked List in C incorrect output -
so i'm doing linked list revison , im trying load list numbers , print out. below code:
#include <stdio.h> #include <stdlib.h> typedef struct stack { int data; struct stack *next; }*stack; stack create_s(void){ stack s = (void*)malloc(sizeof(stack)); s->next = null; homecoming s; } void push_s(stack s, int data) { while (s->next != null) { s = s->next; } s->next = (void*)malloc(sizeof(stack)); s=s->next; s->data = data; s->next = null; } void print_s(stack s) { if (s==null) { return; } else { while (s->next != null) { printf("%d\n",s->data); s=s->next; } } } int main (void) { stack s = create_s(); push_s(s,2); push_s(s,4); push_s(s,6); push_s(s,8); print_s(s); homecoming 0; } my output however:
-1853045587 2 4 6 when should be
2 4 6 8 is printing address of struct @ beginning? also, why not printing lastly element?
thanks
the code contains several errors, first thing catches eye memory allocation broken
stack s = (void*)malloc(sizeof(stack)); you defined stack pointer type. means sizeof(stack) evaluates pointer size , above malloc allocates plenty space store single pointer, not plenty entire struct stack object. same memory allocation error nowadays in push_s well.
here's advice
don't hide pointer types behind typedef names. define stack as
typedef struct stack{ int data; struct stack *next; } stack; and utilize stack * wherever need pointer. i.e. create * visible instead of hiding "inside" typedef name. create code easier read.
don't cast result of malloc. anyway, point of casting void * when void * already???
don't utilize sizeof types unless really have to. prefer utilize sizeof expressions. larn utilize next malloc idiom
t *p = malloc(sizeof *p); or, in case
struct stack *s = malloc(sizeof *s); this allocate memory block of appropriate size.
also, @whozcraig noted in comments, first node in list apparently supposed serve "sentinel" head node (with undefined data value). in code never initialize data value in head node. yet in print_s function effort print data value head node. no wonder garbage (-1853045587) first line in output. don't print first node. skip it, if supposed serve sentinel.
also, cycle termination status in print_s looks strange
while (s->next != null) why checking s->next null instead of checking s itself? status terminate cycle prematurely, without attempting print lastly node in list. reason why don't see lastly element (8) in output.
c linked-list output
No comments:
Post a Comment