【发布时间】:2013-12-12 09:23:28
【问题描述】:
我需要弄清楚如何将两个不同的结构传递给一个函数。我尝试使用 void * 作为参数,但收到错误:
warning: dereferencing 'void *' pointer
error: request for member left in something not a structure or union
会员权限同样的错误
这是我所做的一般性术语(代码可能无法编译)。
struct A{
char *a;
struct A *left, *right;
} *rootA;
struct B{
char *b;
struct B *left, *right;
} *rootB;
void BinaryTree(void *root, void *s){
if(condition)
root->left=s;
else if(condition)
BinaryTree(root->left, s);
if(condition)
root->right=s;
else if(condition)
BinaryTree(root->right, s);
}
int main(){
// Assume the struct of nodeA and nodeB get malloc()
// as well as the variables a and b with actual data.
struct A nodeA;
struct B nodeB;
BinaryTree(rootA, nodeA);
BinaryTree(rootB, nodeB);
return 0
}
【问题讨论】:
-
您的代码表明您没有传递指针。你的意思是
BinaryTree(rootA, &nodeA)等? -
我正在传递nodeA和nodeB的内存位置。函数参数中的 void 指针应该取消引用它以便在函数号中使用?
-
你的参数类型是指针。您正在传递整个结构,而不是指向该结构的指针。尽管除此之外也可能存在问题。编译器不会将结构“取消引用”到 void 指针。
-
当您假设
root是一些包含left的结构时,void *指针的解引用发生在函数BinaryTree中。由于struct A和struct B是相同的,因此重构void *参数并将其转换为指向您的结构的指针.. -
我指的是
nodeA参数。此外,在函数内部,函数知道第一个参数为void *,因此它不会知道root->left是什么。您需要执行类似((struct A *)root)->left之类的操作,这意味着您需要知道root属于哪个结构。
标签: c pointers struct malloc void