C - 函数结构

时间:2015-02-11 11:52:03

标签: c function struct

所以我对C编程还很陌生。我学过Python,所以我对一些代码很熟悉。

例如,当我在python中创建一个函数时,我能够使它适用于不同的类。

我想在这里做类似的事情。我有两个看起来几乎相同的结构。我想对struct两个使用相同的函数,但是当然我不能将struct名称作为参数发送到函数中。我该怎么办?

现在不用担心这个功能的作用。它的原则是能够在同一个函数中使用两个struct s对我来说很重要。如果这是一个完全错误的观点,那么我很抱歉,但这是我在遇到这个问题时的第一个想法。

typedef struct{
   int number;
   struct node *next;
}struct_1;

struct node *head;

typedef struct{
   int number;
   struct node *next;
}struct_2;

void main()
{
   int number1 = 10;
   int number2 = 20;
   function(number1);
   function(number2);
}

void function(int x, struct) // Here is where I want to be able to use 2 different structs for the same function
{
   struct *curr, *head;
   curr=(node1*)malloc(sizeof(node1));
   printf("%d", curr->number);
}

4 个答案:

答案 0 :(得分:2)

C不像Python那样使用duck typing,所以你不能传递一个看起来像其他完全不相关的结构的结构,好像它是这个其他结构一样。

答案 1 :(得分:2)

您可以拥有一个结构的两个实例 该函数可以接受任一实例并根据需要处理它。

typedef struct{
    int number;
    struct node *next;
}mystruct;
void function(int x, mystruct *eachstruct);//prototype
int main()
{
    int number1 = 10;
    int number2 = 20;
    //declare two instances of mystruct
    mystruct list_1 = { 0, NULL};
    mystruct list_2 = { 0, NULL};
    // call the function with one or the other instance of mystruct
    function(number1, &list_1);
    function(number2, &list_2);
}

void function(int x, mystruct *eachstruct)
{
    //do stuff in function
    eachstruct->number = x;
    if ( eachstruct->next == NULL)
    {
        //do more stuff
    }
}

答案 2 :(得分:0)

不幸的是,C无法做你想做的事。

您的选择是:

  1. 重构代码以对所有项使用相同的结构类型。
  2. 将结构中感兴趣的字段直接传递给函数
  3. 编写代码以将类似的结构封送到一个公共结构。
  4. 使用类型系统快速放松,并在两个不同的结构中以相同的方式安排共享元素并投射指针。
  5. If you just want a linked list check out how code re-use is achieved in the linux kernel

答案 3 :(得分:0)

答案:不,你不能直接这样做。欢迎来到静态打字。

有一种方法可以通过使用我们心爱的虚空*和一些铸件来实现类似的东西但是,相信我,这不是你想要做的。如果你真的想这样做,请直接询问。你被警告了。

相关问题