【问题标题】:Accessing the members of a struct referenced by a void pointer访问由 void 指针引用的结构的成员
【发布时间】:2019-07-12 15:50:23
【问题描述】:

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

编辑:修正了文章中的一些错别字

【问题讨论】:

  • 投票结束是一个错字。 s2 = *(struct s)p_obj; 必须是 s2 = *(struct s*)p_obj;
  • 为什么要编写类似 C 的代码?显然有人是teaching you c++ in wrong way(链接是给你的老师的)。
  • Marek,我遵循公司风格指南。 耸耸肩
  • 这里有官方cpp core guidelines。

标签: c++


【解决方案1】:

你有两个错误:

  1. *(struct s)p_obj 必须是*(struct s*)p_obj,因为p_obj 不是结构对象。

  2. 因为operator precedence,表达式(struct s*)p_obj-&gt;val实际上等于(struct s*)(p_obj-&gt;val)。这意味着您尝试取消引用 void* 指针并将成员 val 强制转换为 struct s*。

    您应该使用((struct s*)p_obj)-&gt;val 来投射指针p_obj。

还有更多错别字:*void p_obj 非常错误,应该是void* p_obj。请注意复制粘贴您的minimal, complete, and reproducible example,不要重新输入,因为这可能会在您的真实代码中添加额外的错误,从而分散实际错误和问题的注意力。

【讨论】:

  • 1.在我的文章中是一个错字,我的错。我运行的代码确实使用了 *(struct s*)p_obj.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-05
  • 2014-05-14
  • 1970-01-01
  • 1970-01-01
  • 2021-04-14
  • 2016-05-24
  • 1970-01-01
相关资源
最近更新 更多