Search code examples
cpointersvoid

Void pointer value doesn't change when changed in function


So, I am trying to test if my void* value is correct, but it keeps saying it's NULL although I know it does change in my function. TestCode:

  void test_mystack_push_and_pop(void)
 {
   void* obj;
   mystack_pop(1, &obj);
   TEST_ASSERT_EQUAL(12, (intptr_t)obj);
 }

Mystack_pop:

int mystack_pop(int handle, void* obj)
{
    pStackMeta_t tmpStackList = gStackList;
    obj = tmpStackList->stack->obj;
    tmpStackList->stack = tmpStackList->stack->next;
    tmpStackList->numelem -= 1;
    DBG_PRINTF("handle: %d, obj: %p\n", handle, obj);
    return 0;
}

So, if I check the value of obj in mystack_pop it is not null but then in the test it is still null. I've tried it all but can't get it to work.


Solution

  • If you want to update a pointer parameter, you need to pass it as **ptr. By writing **Ptr you state that your output parameter Ptr is a pointer on a pointer. So a pointer on a variable of type pointer. Try:

    int mystack_pop(int handle, void **obj)
    {
        pStackMeta_t tmpStackList = gStackList;
        *obj = tmpStackList->stack->obj;
        tmpStackList->stack = tmpStackList->stack->next;
        tmpStackList->numelem -= 1;
        DBG_PRINTF("handle: %d, obj: %p\n", handle, *obj);
        return 0;
    }