访问由 void 指针引用的结构的成员
Accessing the members of a struct referenced by a void pointer
>我有一个函数,它将 void 指针作为参数。我想向此函数传递指向结构的指针,然后在函数中访问该结构的值。
//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
。
还有更多的错别字:*void p_obj
大错特错,应该void* p_obj
.请注意复制粘贴您的最小、完整且可重现的示例,而不是重新键入,因为这可能会在您的实际代码中添加额外的错误,从而分散对实际错误和问题的注意力。
相关文章:
- 具有结构成员char数组的sscanf
- 仅使用结构名称访问结构成员
- 使用 structType*& 赋给结构成员
- 使用结构成员指针在C++中填充结构
- 聚合初始化,将成员指针设置为同一结构成员
- 为什么结构化绑定不使用"auto&"返回对结构成员的引用,而是返回成员本身
- 是否可以将结构数组别名为结构成员数组?
- 结构成员在访问时被清除
- 如何指示结构成员没有锯齿?
- 为什么继承的结构成员在联合中无法访问?
- 尝试在 qml 中访问结构成员的 QList
- C++/CLI -- 访问结构成员
- 调用在类中声明的结构成员
- 对结构成员的临时绑定引用
- 无法使用 strcpy 将字符串复制到静态结构成员
- 为什么类成员数据必须是静态的才能被模板化类的模板化结构成员访问
- 填充模板化结构类型的结构成员
- C/C++intellisense 0.26.1不显示结构成员列表
- 在源文件中创建具有结构成员的结构
- 如何访问结构成员作为指针