droman07
droman07

Reputation: 127

In C++, I'm getting a message "error: 'void*' is not a pointer-to-object type"

Here's my code:

#include <iostream>
using namespace std;

int main()
{
   void *x;
   int arr[10];
   x = arr;
   *x = 23; //This is where I get the error
}

As you can see, the code is very simple. It just creates a void pointer x which points to the memory address of the array 'arr' and puts the integer 23 into that memory address. But when I compile it, I get the error message "'void*' is not a pointer-to-object type". When I use an 'int' pointer instead of a void pointer and then compile it, I don't get any errors or warnings. I wanna know why I get this error.

Thank you.

Upvotes: 1

Views: 7904

Answers (3)

Mohammad Kanan
Mohammad Kanan

Reputation: 4582

you cant derefrence void*, and that is what the coder is doing.

*x = 23; // this cant be done with void*

instead :

x = &arr[index] ; // this is correct

Upvotes: 1

Bull Bullz
Bull Bullz

Reputation: 1

The compiler needs the type of the variable to to dereference the pointer.

only example no malloc: *int myPtnr = 0x12345;

When you write

*myPtr = NUMBER:

The compiler looks at the type and say .. okay here we have a int ... the Information i need are in the next 4 bytes starting with the adress of the pointer.

Thats the reason why you have to tell the compiler the type. When you use void the compiler dont know how much bytes he has to use for dereference.

Upvotes: 0

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

As the compiler message says, void* is not a pointer to object type. What this means is that you cannot do anything with void*, besides explicitly converting it back to another pointer type. A void* represents an address, but it doesn’t specify the type of things it points to, and at a consequence you cannot operate on it.

Upvotes: 9

Related Questions