将不同的结构传递给函数(使用void *)

我需要弄清楚如何将两个不同的结构传递给一个函数。 我尝试使用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 } 

您对结构声明感到困惑。 类型由struct后面的单词给出。 最后需要做的事情,至少在你了解typedef之前。 例:

 struct A{ char *a; struct A *left, *right; }; 

当你调用BinaryTree时,你需要总是传递指针而不是结构。 例:

 BinaryTree(&nodeA, &nodeA); 

对void指针执行操作时,需要先将其强制转换为正确的指针类型。 例:

 (struct A*)root->left=s; 

将这些结构作为无效指针传递绝对是不好的做法,你会让自己感到非常困惑。 空位指针应谨慎使用。 由于您似乎是从C开始,我建议您不要使用它们,直到您更好地理解值和引用语义。 话虽这么说,当我开始使用C时,我做了很多愚蠢的代码,有时仍然会这样做。 你会随着时间和练习弄清楚。

您的程序有两个方面需要重新查看。 一,是通过值而不是引用传递的参数。 因此,对BinaryTree函数的调用应具有

 BinaryTree(rootA, &nodeA); 

另一个主要考虑因素是如何在BinaryTree函数中处理这些void指针。 在目前的forms,

 void BinaryTree(void *root, void *s){ if(condition) root->left=s; 

这里的root是一个void * ,因此无法计算root->left 。 因此,您需要将root 类型转换为有意义的数据类型

 struct A *hdl = (struct A*)(root); hdl->left = s; 

即使采用这种方法,一个更重要的考虑因素是您对不同的结构使用相同的function。 因此,知道什么时候输入施放root作为AB将是困难/具有挑战性的,因此,该策略需要小的重新思考。