[英]Accessing the members of a struct referenced by a void pointer
我有一个函数,将空指针作为参数。 我想将此函数的指针传递给结构,然后在函数中访问该结构的值。
//the struct
struct s{
int val;
};
//the function tries to access the object
int callback(void* p_obj)
{
//try creating a new struct based on p_obj
s2 = *(struct s*)p_obj;
std::cout << "VALUE IN CALLBACK: ";
std::cout << s2.val << std::endl; //prints a big-ass int
return 0;
}
//main calls the function
int main()
{
s s1;
s1.val = 42;
void* p1 = &s;
//show some output
std::cout << "s1.val: ";
std:cout << s1.val << std::endl; //prints 42
//std::cout << "p1->val: ";
//std:cout << *(struct s*)p1->val << std::endl; //does not compile
s p2 = *(struct s*)p1;
std::cout << "p2.val: ";
std:cout << p2.val << std::endl; //prints 42
//call the function
callback(&p1);
return 0;
}
我希望回调函数中的输出是
VALUE IN CALLBACK: 42
VALUE IN CALLBACK: 42
但是,相反,我认为它正在打印一个内存地址
VALUE IN CALLBACK:1989685088
VALUE IN CALLBACK:1989685088
尝试访问void指针的成员将直接导致错误。
int callback(void* p_obj)
{
std::cout << "VALUE IN CALLBACK: ";
std::cout << (struct s*)p_obj->val << std::endl;
}
error: 'void*' is not a pointer-to-object type
为什么是这样? 如何访问void *指向的结构的成员?
编辑:修复了一些打字错误
您有两个错误:
*(struct s)p_obj
必须是*(struct s*)p_obj
,因为p_obj
不是结构对象。
由于运算符的优先级 ,表达式(struct s*)p_obj->val
实际上等于(struct s*)(p_obj->val)
。 这意味着您尝试取消引用void*
指针,并将成员val
为struct s*
。
您应该执行((struct s*)p_obj)->val
以p_obj
指针p_obj
。
还有更多错别字: *void p_obj
非常错误,应该为void* p_obj
。 请小心复制并粘贴您的最小,完整且可复制的示例 ,而不是重新输入,因为这样可能会在您的真实代码中添加额外的错误,从而分散了实际的错误和问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.