c/c++语言开发共享将不同的结构传递给函数(使用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将是困难/具有挑战性的,因此,该策略需要小的重新思考。

      以上就是c/c++开发分享将不同的结构传递给函数(使用void *)相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/549167.html

      (0)
      上一篇 2021年1月13日
      下一篇 2021年1月13日

      精彩推荐