배우고픈 공돌이
범용 스택 본문
//main.c #include <stdio.h> #include "stack.h" int main(void) { stack_t s1, s2; initStack(&s1,10,sizeof(int)); initStack(&s2,100,sizeof(double)); int i=100; push(&s1,&i); i=200; push(&s1,&i); i=300; push(&s1,&i); double j = 900.9; push(&s2,&j); j=800.8; push(&s2,&j); j=700.7; push(&s2,&j); pop(&s1,&i); printf("s1 1st pop : %d \n",i); pop(&s1,&i); printf("s1 2nd pop : %d \n",i); pop(&s1,&i); printf("s1 3rd pop : %d \n",i); pop(&s2,&j); printf("s2 1st pop : %f \n",j); pop(&s2,&j); printf("s2 2nd pop : %f \n",j); pop(&s2,&j); printf("s2 3rd pop : %f \n",j); cleanupStack(&s1); cleanupStack(&s2); return 0; }
//stack.c #include "stack.h" #include <stdlib.h> #include <stdio.h> #include <assert.h> #include <string.h> void initStack(stack_t* s, int size, int element_size) { s -> pArr = malloc(element_size*size); assert( s->pArr ); s -> element_size = element_size; s -> size = size; s -> tos = 0; } void cleanupStack(stack_t* s) { free( s->pArr ); } void push(stack_t* s,const void* pData) { assert( s->tos != s->size); //memcpy(&s->pArr[(s->tos)++], pData, s->element_size); //&s->pArr[(s->tos)++] -> dereference error memcpy((unsigned char*)s->pArr+((s->tos) * (s->element_size)), pData,s->element_size); (s->tos)++; //int a ; a++ = 4byte //double b; b++ = 8byte //void c; c++ = 1byte } void pop(stack_t* s, void* pData) { assert( s->tos != 0 ); //memcpy(pData,&s->pArr[--(s->tos)],s->element_size); (s->tos)--; memcpy(pData,(unsigned char*)s->pArr+((s->tos)*(s->element_size)),s->element_size); }
//stack.h #ifndef STACK_H #define STACK_H typedef struct { void* pArr; int element_size; int tos; int size; } stack_t; void initStack(stack_t* s, int size, int element_size); void cleanupStack(stack_t* s); void push(stack_t* s, const void* pData); void pop(stack_t* s, void* pData); #endif
Comments