I am implementing generic stack in C and I am facing a problem in stackPop method. My struct is as follows:
\"Stack.h\" file
I think the best you could do is to return a pointer to popped data (as a void*
since that's about the best you can do in C for a '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;
}
Note that the caller still needs to provide the memory and the address to pop the data into; if you want ed you could avoid that by having the function malloc()
the 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 that would require the caller to free()
it when it is no longer needed, and adds the minor complication of needing to handle the out of memory situation.