Generic Stacks in C

前端 未结 1 1477
攒了一身酷
攒了一身酷 2021-01-13 13:41

I am implementing generic stack in C and I am facing a problem in stackPop method. My struct is as follows:

\"Stack.h\" file

             


        
相关标签:
1条回答
  • 2021-01-13 14:07

    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.

    0 讨论(0)
提交回复
热议问题