问题描述
这是我的代码:
#include <iostream>
using namespace std;
int main()
{
void *x;
int arr[10];
x = arr;
*x = 23; //This is where I get the error
}
如您所见,代码非常简单.它只是创建一个空指针x,该指针指向数组"arr"的内存地址,并将整数23放入该内存地址.但是,当我对其进行编译时,会收到错误消息'void *'不是指针到对象的类型".当我使用'int'指针而不是void指针进行编译时,我没有收到任何错误或警告.我想知道为什么会收到此错误.
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.
谢谢.
推荐答案
如编译器消息所述,void*
不是指向对象类型的指针.这意味着您不能使用void*
进行任何操作,除了将其显式转换回另一种指针类型. void*
代表地址,但未指定其指向的内容的类型,因此您无法对其进行操作.
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.
这篇关于在C ++中,我收到一条消息“错误:'void *'不是指向对象的指针类型".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!