Hi
Currently I am implementing a generic(int plus float etc) stack in C. However I am facing some problems.
stackgen.h
stackgen.c
The above code works absolutely fine. But what i need is the functionality that user enter either int or float at run time and push gets called accordingly. I do not want to ask from the user whether next input he will enter would be an int or float? How can I accomplish this?
Currently I am implementing a generic(int plus float etc) stack in C. However I am facing some problems.
stackgen.h
Code:
#define STACKSIZE 100 #define INTEGER 1 #define FLOAT 2 #define STRING 3 struct stackelement { int etype; union { int i; float f; }element; }; struct stack { int top; struct stackelement items[STACKSIZE]; }; void init(struct stack *); void printtop(struct stack *); void push(struct stack *,int,void);
Code:
#include "stackgen.h" void init(struct stack *mycopy) { mycopy->top=-1; } void printtop(struct stack *mycopy) { struct stackelement se; se=mycopy->items[mycopy->top]; //printf("%d",se.etype); switch(se.etype) { case INTEGER: printf("%d\n",se.element.i); break; case FLOAT: printf("%f\n",se.element.f); break; } } void push(struct stack *mycopy,int etype,void *item) { int *intptr; float *floatptr; (mycopy->top)++; mycopy->items[mycopy->top].etype=etype; switch(etype) { case INTEGER: intptr=(int *)item; (mycopy->items[mycopy->top].element.i)=*intptr; break; case FLOAT: floatptr=(float *)item; (mycopy->items[mycopy->top].element.f)=*floatptr; break; } } int main() { struct stack my; init(&my); int i=100; float f=23.23; push(&my,1,&i); push(&my,2,&f); printtop(&my); return 0; }
Comment