Void* - casting

Hello again.

Thanks to the help of some people in here, I have written a dynamic stack that takes void* in it's nodes. Now, I want to check that it works.
How can I check the values that the loop gives are actually being pushed?
As I want to stack ints, I ought to cast them, and then cast the top of the stack, right?
What's wrong in here for me not to get 0123456... with printf?

1
2
3
4
5
6
7
8
9
10
void stack_test_push (stack_t* stack)
{
    for (int i=0; i<=201;i++)
        {
            stack_push(stack,(void*)i);
            void* value = stack_peek_top(stack);
            printf("%i", (int)value);
        }
}
How does your stack work? Is it a stack of void* that point to individual items? In that case, you need to create a new integer on the heap with the value of i and give that address to your stack.

Currently, you are instead pretending (by casting) whatever number you have (0, 1, 2, and so on) is a valid address.
I'm sorry, I don't quite get it.

The implementation of the stack uses a vector that, yes, contains void*.

What I want to do is to push values into each vector space. It contains void* so there's casting involved and I don't quite know how to save/cast that data.

I try to access the heap by using malloc and I try to give newint the address of the iterator "i" as in the loop mentioned above, and pass that to the stack_push function, but that gives me a segfault.
1
2
3
4
5
6
7
8
9
10
11
12
void stack_test_push (stack_t* stack)
{
    for (size_t i=0; i<=201;i++)
        {
            size_t* p_i = malloc(sizeof(size_t));
            *p_i = i;
            stack_push(stack, (void*)p_i);  //not casting it doesn't make a difference

            void* value = stack_peek_top(stack);
            printf("%i", (int)value);
        }
}
Last edited on
Sorry for the double post but the thread was two pages back and I need some more help :)

What am I doing wrong and how can I right it?
Change line 10:

printf("%i", *((int*)value)); // Note: Cast to pointer not to value
Still getting segfault... but the error here is gone. Thank you.
Topic archived. No new replies allowed.