将不同的结构传递给函数(使用void *) [英] passing different structs to a function(using void *)

查看:77
本文介绍了将不同的结构传递给函数(使用void *)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要弄清楚如何将两个不同的结构传递给一个函数.我尝试使用void *作为参数,但收到错误:

I need to figure out how to pass two different structs to a function. I tried using void * for the parameter but i am receiving the error:

warning: dereferencing 'void *' pointer
error: request for member left in something not a structure or union

成员权限相同错误

这是我一般而言所做的(代码可能无法编译).

here is what i did in general terms(code may not compile).

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之前,都需要解决这一问题.示例:

You are confused on your struct declarations. The type is given by the word after struct. That thing at the end needs to go, at least until you learn about typedefs. Example:

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

当您调用BinaryTree时,需要始终将其传递给指针而不是结构.示例:

When you call BinaryTree you need to always pass it pointers not structs. Example:

BinaryTree(&nodeA, &nodeA);

对空指针进行操作时,需要首先将其强制转换为正确的指针类型.示例:

When you do operations on a void pointer, you need to cast it to the correct pointer type first. Example:

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

将这些结构作为空指针传递绝对是一种不好的做法,您会感到非常困惑.虚空指针应谨慎使用.由于您似乎是从C入手的,因此建议您完全不使用它们,直到您对值和引用语义有了更好的了解.话虽这么说,当我开始使用C时,我做了很多愚蠢的代码,有时还是会做.您将通过时间和实践来弄清楚.

Passing these structs around as void pointers is definitely bad practice and you will get yourself horribly confused. Void pointers are to be used sparingly. Since you seem to be starting on C, I recommend you don't use them at all yet until you understand value and reference semantics a little better. That being said, I made lots of stupid code when I started on C, still do sometimes. You'll figure it out with time and practice.

这篇关于将不同的结构传递给函数(使用void *)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆