Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why trying to deference void pointer does not work?

Tags:

c

pointers

int main()
{
    int b = 12;
    void *ptr = &b;
    printf("%d", *ptr);
    return 0;
}

I expected for this code to print 12, but it does not. if instead of void pointer, we define int pointer it would work. I wanted to know how can we use void pointer and print the address allocated to it and the amount saved in it?

like image 216
sajjad eshghi Avatar asked Jun 15 '26 18:06

sajjad eshghi


2 Answers

Dereferencing a void * doesn't make sense because it has no way of knowing the type of the memory it points to.

You would need to cast to pointer to a int * and then dereference it.

printf("%d", *((int *)ptr));
like image 160
dbush Avatar answered Jun 17 '26 10:06

dbush


void pointers cannot be dereferenced.it will give this warning

Compiler Error: 'void' is not a pointer-to-object type*

so, you have to do it like this.

#include<stdio.h>
int main()
{
    int b = 12;
    void *ptr = &b;
    printf("%d", *(int *)ptr);
    return 0;
}
like image 44
Peaky_001 Avatar answered Jun 17 '26 09:06

Peaky_001



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!