Common Stacks in C

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.

+4
source share
1 answer

I think the best thing you could do is return a pointer to the popup data (like void* , since this is the best thing you can do in C for the "generic" function):

 void* stackPop(Stack *s, void *elemAddr){ void *source = (char *)s.elems + (s.logLength-1)*s.elemSize; memcpy(elemAddr,source,s.elemSize); s.logLength--; return elemAddr; } 

Please note that the caller still needs to provide a memory and address for data entry; if you want ed, you can avoid this by having the malloc() function in memory:

 void* stackPop(Stack *s){ void *source = (char *)s.elems + (s.logLength-1)*s.elemSize; void *elemAddr = malloc(s.elemSize); // if (!elemAddr) handle_error(); memcpy(elemAddr,source,s.elemSize); s.logLength--; return elemAddr; } 

Of course, this requires that the caller is free() when it is no longer needed, and adds a secondary complication to the need to cope with a lack of memory.

+6
source

Source: https://habr.com/ru/post/1436516/


All Articles