c - How do get void pointers working as desired below in the description? -
i trying implement stack in c program. header file of program, stack.h
.
#ifndef stack_h #define stack_h typedef struct node { void *data; struct node *next; }stack; void push(stack **, void *); void *pop(stack **); void *peek(stack **); #endif
this implementation of functions, in stack.c
file.
#include <stdlib.h> #include "stack.h" void push(stack **top, void *data) { stack *ptr; ptr = (stack *)malloc(sizeof(stack)); if(!ptr) return; ptr->data = data; ptr->next = *top; *top = ptr; } void *pop(stack **top) { stack *ptr; void *data; ptr = *top; *top = ptr->next; data = ptr->data; free(ptr); return data; } void *peek(stack **top) { stack *ptr; ptr = *top; return ptr->data; }
this main.c
file.
#include <stdio.h> #include "stack.h" int main() { int count; stack *top = null; for(count = 0; count < 100; count += 10) push(&top, &count); while(top != null) printf("%d\n", *(int *)pop(&top)); }
this prints out 100
11 times this:
100 100 100 100 100 100 100 100 100 100 100
while should have printed this:
100 90 80 70 60 50 40 30 20 10 0
well, know why happening. because passing address count
variable stored regardless of value contains. hence, last value pushed in stack 10 times.
but when modify main.c
this:
#include <stdio.h> #include "stack.h" int main() { stack *top = null; int = 5; char b = 'a'; float c = 15.98; long d = 225678460; push(&top, &a); push(&top, &b); push(&top, &c); push(&top, &d); printf("%ld\n", *(long *)pop(&top)); printf("%f\n", *(float *)pop(&top)); printf("%c\n", *(char *)pop(&top)); printf("%d\n", *(int *)pop(&top)); }
then output desired as:
225678460 15.980000 5
how should modify 1st main.c
in order desired output in 2nd main.c
?
thanks in advance biggest of programming life. college project.
because stack holds pointers values, , not literal values, have hold values @ different addresses. if use 1 variable in loop, storing values successively same address. nodes on stack pointing 1 address.
to around this, can allocate memory on heap each value. this:
for(count = 0; count < 100; count += 10) { int *ptr = malloc(sizeof(int)); *ptr = count; push(&top, (void*)ptr); }
in case, exiting after printing values on stack, can away without free
ing allocated memory. freed when program exits. if doing in real program, make sure free
memory allocated each value when don't need more. or, more realistically, if want stack of integers, make each node hold int
rather void pointer.
Comments
Post a Comment