GG33
GG33

Reputation: 33

Void pointers in c

I wrote these lines of code expecting them to work just fine but I keep getting an error that 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.

Upvotes: 0

Views: 79

Answers (3)

Eric Postpischil
Eric Postpischil

Reputation: 222362

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.

Upvotes: 2

Mureinik
Mureinik

Reputation: 311163

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

Upvotes: 1

Substitute
Substitute

Reputation: 269

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*).

Upvotes: 1

Related Questions