值分配到取消引用空指针 [英] Assign values to a dereferenced void pointer
问题描述
我在做C ++中的类,它支持任何类型的变量来帮助我在未来的项目中。问题是,当我试图分配一个值到无效*
变量,我得到的错误:无效*
不是指针到对象的类型。这里是code:
I'm doing a class in c++ that supports any kind of variable to help me in a future project. The thing is, when I try to assign a value to a void*
variable, I get the error: void*
is not a pointer-to-object type. Here is the code:
int main (void) {
void* a;
int x;
a = malloc(sizeof(int));
x = 120;
((int)(*a)) = x;
printf("%d",((int)*a));
free(a);
system("pause");
return 0;
}
我看到它就像我试图在分配为保留的内存块x的值。欲存储在x中的值被存储在一个存储块。可以any1能帮助我吗?
I see it like I am trying to assign the value of x in the memory block reserved for a. I want that the value stored in x be stored in the memory block of a. Can any1 help me?
推荐答案
首先,你必须投 A
到相应的指针类型和然后的去引用它。其次,用一个模板 - 这就是他们的东西。第三,malloc和free是baaaad,OK?别。如果你认为这是很好的code,你需要认真采取补救C ++。第四,这已经done- 的boost ::任何
服务于这个目的。
Firstly, you must cast a
to the appropriate pointer type and then de-reference it. Secondly, use a template- that's what they're for. Thirdly, malloc and free is baaaad, OK? Don't. If you think that this is good code, you need serious remedial C++. Fourthly, this is already done- boost::any
serves this purpose.
这篇关于值分配到取消引用空指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!