简体   繁体   中英

Accessing the members of a struct referenced by a void pointer

I've got a function that takes a void pointer as a parameter. I want to pass this function a pointer to a struct, and then access the values of that struct within the function.

//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;
}

I would expect the output in the callback function to be

VALUE IN CALLBACK: 42
VALUE IN CALLBACK: 42

but, instead, I think it's printing a memory address

VALUE IN CALLBACK:1989685088
VALUE IN CALLBACK:1989685088 

Trying to access the members of a void pointer directly results in an error.

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

Why is this? How can I access the members of a struct that a void* is pointing to?

EDIT: Fixed some typos in the writeup

You have two errors:

  1. *(struct s)p_obj needs to be *(struct s*)p_obj , as p_obj is not a structure object.

  2. Because of operator precedence the expression (struct s*)p_obj->val is actually equal to (struct s*)(p_obj->val) . Which means you try to dereference the void* pointer and cast the member val to struct s* .

    You should do ((struct s*)p_obj)->val to cast the pointer p_obj .

And more typos: *void p_obj is very much wrong, it should be void* p_obj . Please take care to copy-paste your minimal, complete, and reproducible example , not retype is as that might add extra errors not in your real code, which distracts from the actual errors and problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM