繁体   English   中英

C-函数结构

[英]C - Functions Structs

所以我对C编程还是很陌生的。 我虽然已经学习过Python,所以对某些代码还是很熟悉。

例如,当我在python中创建函数时,我可以使其通用且可用于不同的类。

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

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

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);
}

C不像Python那样使用鸭子类型,因此您不能传递看起来像其他完全无关的结构的结构,就好像它是另一结构一样。

您可能有一个结构的两个实例。
该函数可以接受任何一个实例,并根据需要对其进行处理。

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
    }
}

不幸的是,C无法做到您想要的。

您的选择是:

  1. 重构代码以对所有项目使用相同的结构类型。
  2. 将结构中感兴趣的字段直接传递给函数
  3. 编写代码将类似的结构编组为通用结构。
  4. 快速,轻松地使用类型系统,并在两个不同的结构中以相同的方式排列共享元素,然后投射指针。

如果您只想要一个链表,请查看如何在Linux内核中实现代码重用

答:不,您不能直接这样做。 欢迎使用静态输入。

有一种方法可以通过使用我们钟爱的void *和一些转换来实现相似的目的,但是,请相信我,这不是您想要做的。 如果您确实要这样做,请直接询问。 你被警告了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM