Home > Back-end >  Void pointers in c
Void pointers in c

Time:12-24

I just wrote this lines of code expecting them to work just fine but I keep getting an error which says "invalid use of void expression" and i have no clue why

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

I thought void pointers can point to any type of data so what's the issue here. I even tried to cast the void pointer to an integer pointer but I still get the same error.

CodePudding user response:

You can not dereference a void pointer, the underlying type (void) is incomplete. You should either use a different type for your pointer (such as int*) or you should cast your void pointer to a complete type (again, probably int*).

CodePudding user response:

You can't dereference a void*, as you've seen, but casting it to an int* most definitely works:

printf("%d",*(int*)ptr);

OnlineGDB demo

CodePudding user response:

I thought void pointers can point to any type of data so what's the issue here.

A void * can point to any type of data1. But it only remembers the address, not the type. To use it with *, you must tell the compiler what type to use:

int a = 12;
void *ptr = &a;
printf("%d\n", * (int *) ptr);  // Use cast to specify type.

During execution, the program will not remember that ptr was assigned an address from an int and automatically know to load an int in the printf call. During compilation, the compiler will not remember this either. To use the pointer to access data, you must convert it back to an appropriate type, then use that.

Footnote

1 A pointer should retain all the qualifiers of any object it is set to point to. A pointer to a const int x or volatile int x ought to be assigned to a const void *p or a volatile void *p, respectively, not a void *p without the qualifiers.

  • Related