[英]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.