简体   繁体   English

'void *'不是指向对象的指针类型

[英]‘void*’ is not a pointer-to-object type

struct limit{
  int up;
  int down;
};

void *x;

struct limit *l;
l->up=1;
l->down=20;

x=l;

cout<<x->up;

This is part of my code I am getting error in last line 'void*' is not a pointer-to-object type . 这是我的代码的一部分,我在最后一行'void *'中出错, 这不是指向对象的指针类型 I know last line in my code is wrong. 我知道代码的最后一行是错误的。 I just want to know how to print up and down values using x variable. 我只想知道如何使用x变量上下打印值。

In this part: 在这一部分:

struct limit *l;
l->up=1;
l->down=20;

you are dereferencing uninitialized pointer l , which results in undefined behavior . 您正在取消引用未初始化的指针l ,这将导致未定义的行为 However, even if you initialized it properly, after you assign it to void* , you can not dereference void pointer: 但是,即使您正确地初始化了它,将其分配给void* ,也无法取消引用void指针:

void* x = l;
cout<< x->up;

you need to explicitly cast it back to struct limit* : 您需要将其显式转换回struct limit*

void* x = l;
struct limit * y = static_cast<struct limit*>(x);
cout << y->up;

or yet even better: avoid using void* at first place. 甚至更好:避免一开始使用void*


Since you mentioned that you're doing this because of , then this answer will help you :) 既然您提到您是因为这样做的,那么此答案将对您有所帮助:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 错误错误:“ void *”不是指向对象的指针类型 - Error error: ‘void*’ is not a pointer-to-object type “'void *'不是一个没有void *的代码中的指针对象类型”? - “'void*' is not a pointer-to-object type” in code with no void*'s? C++,“错误:&#39;void*&#39; 不是指向对象的类型” - C++, “error: 'void*' is not a pointer-to-object type” C ++。 错误:void不是指向对象的指针类型 - C++. Error: void is not a pointer-to-object type 错误:“ void *”不是指向对象的指针类型正确的解决方案是什么? - error: ‘void*’ is not a pointer-to-object type what is the right solution? sqrt 函数导致“&#39;void*&#39; 不是指向对象类型的指针”错误 - sqrt function causing " 'void*' is not a pointer-to-object type" error 错误:即使指针设置为对象,为什么“void*”也不是指向对象的指针类型? - Error: Why 'void*' is not a pointer-to-object type even though the pointer is set to an object? 在C ++中,我收到一条消息“错误:&#39;void *&#39;不是指向对象的指针类型” - In C++, I'm getting a message “error: 'void*' is not a pointer-to-object type” 收到“ void *不是指向对象的指针类型”错误,但是使用XCode时代码可以完美执行 - Getting “void* is not a pointer-to-object type” error but the code executes perfectly when using XCode 错误:动态打开多个共享库时,“ void *”不是指向对象的指针类型错误 - Error: ‘void*’ is not a pointer-to-object type error while dynamically opening multiple shared libraries
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM