I am implementing a common stack in C, and I ran into a problem in the stackPop method. My structure is as follows:
File "Stack.h"
typedef struct{ void *elems; int elemSize; int allocLength; int logLength; void (*freefnc)(void *); } Stack; void stackNew(Stack *s, int elemSize, void (*freefnc)(void *)); void stackDispose(Stack *s); void stackPush(Stack *s, void *elemAddr); void stackPop(Stack *s, void *target);
Stack.c
#inlcude<Stack.h> void stackNew(Stack *s, int elemSize, void (*freefnc)(void *)){ s.allocLength = 4; s.logLength = 0; s.elemSize = elemSize; s.elems = malloc(4*elemSize); s.freefnc = freefnc; } void stackDispose(Stack *s){ if(s.freefnc!=NULL){ for(int i=0; i<s.logLength; i++){ freefnc((char *)s.elems+i*s->elemSize); } } free(s.elems); } void Stringfree(void *elem){ free(*(char**)elem); } void stackPush(Stack *s, void *elemAddr){ if(s.alloclength == s.logLength){ stackGrow(s); } void *target = (char *)s.elems + s.logLength*s.elemSize; memcpy(target,elemAddr,s.elemSize); s.logLength++; } static void stackGrow(Stack *s){ s.allocLength*=2; s.elems = realloc(s.elems, s.alloclength*s.elemSize); assert(s.elems!=NULL); } void stackPop(Stack *s, void *elemAddr){ void *source = (char *)s.elems + (s.logLength-1)*s.elemSize; memcpy(elemAddr,source,s.elemSize); s.logLength--; }
How to return / get the value that slipped in the stackPop function? I do not want to change the implementation, but if there is a good way to implement the implementation as much as possible, then I would appreciate it. Other approaches are also acceptable.
source share