Search code examples
cpointersdata-structuresstackvoid-pointers

How can I print a (void **) data in C?


I'm having a hard time fully understanding and learning the behavior of pointers, casts, and all that.

I have the following struct, which is basically a stack data structure:

struct stack
{
    void **items;
    size_t top;      
    size_t max_size;
};

I want to be able to return the top element, so this is my Peek function:

void *Peek(const stack_ty *stack)
{
    return(stack->items[stack->top]);
}

And this is my testing print in main.c:

stack_ty *new_stack = CreateStack(5);
 
Push(new_stack, (void *)1);
Push(new_stack, (void *)2);
Push(new_stack, (void *)3);
 
printf("The top element is %d\n", *(int *)Peek(new_stack));

I'm getting a Segmentation fault (core dumped) right after it enters the Peek function.

I can guess it is related to the *(int *) cast I did to the return value of Peek(), but I can't think about any other way to print() or show any value that is passed by void *. I mean, I have to cast it to int * or char * or whatever, right?

What am I doing wrong here? I'll be glad to hear any tips on how to better understand this whole pointers thing. I mean, I thought I was pretty good at it, but I guess I was wrong.

To be honest, in the beginning I thought I needed to cast 1,2 and 3 to (void *)&1, (void *)&2, (void *)&3, because I thought I can't pass them just like that, and I thought that if I want to cast an int to a void * I have to give it the address of the int.

But the compiler screamed at me, so I changed it to Push(new_stack, (void *)3);


Solution

  • Since you're casting an int to a void * when you push, you need to cast it back to an int when you peek, not to an int *. You're not storing a pointer to an integer in the stack, you're treating the integer itself as if it were a pointer.

    printf("The top element is %d\n", (int)Peek(new_stack));