访问由 void 指针引用的结构的成员

Accessing the members of a struct referenced by a void pointer

本文关键字:结构 成员 引用 指针 void 访问      更新时间:2023-10-16

>我有一个函数,它将 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* 指向的结构的成员?

编辑:修复了文章中的一些拼写错误

您有两个错误:

  1. *(struct s)p_obj需要*(struct s*)p_obj,因为p_obj不是一个结构对象。

  2. 由于运算符优先级,表达式 (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.请注意复制粘贴您的最小、完整且可重现的示例,而不是重新键入,因为这可能会在您的实际代码中添加额外的错误,从而分散对实际错误和问题的注意力。