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

后端 未结 3 1931
死守一世寂寞
死守一世寂寞 2021-01-24 09:08

Here\'s my code:

#include 
using namespace std;

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


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-24 09:46

    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.

提交回复
热议问题