【问题标题】:C - Functions StructsC - 函数结构
【发布时间】:2015-02-11 11:52:03
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • able to use你能澄清一下吗?"
  • struct_1struct_2 在您的示例中具有相同的成员。你想达到什么目标?您想要各种类型有效负载的链表吗?
  • 这是一个完全错误的观点。不要尝试将 Python 动态类型应用于 C。如果您有两个结构 - 即使具有相同的字段 - 对于 C,它们是不同的,仅此而已。有一些技巧可以规避这一点,但由于您是 C 新手,所以不要从技巧开始。
  • @diaco 为什么你一开始就需要两个结构来做同一件事?
  • 你想要一个结构的两个副本。不是两种不同的数据类型。

标签: c function struct


【解决方案1】:

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

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】:

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

    【讨论】:

      【解决方案3】:

      不幸的是,C 不能做你想做的事。

      您的选择是:

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

      If you just want a linked list check out how code re-use is achieved in the linux kernel

      【讨论】:

        【解决方案4】:

        回答:不,你不能直接这样做。欢迎使用静态类型。

        有一种方法可以通过使用我们心爱的 void * 和一些铸件来实现类似的效果,但请相信我,这不是您想要做的。如果你真的想这样做,直接要求它。您已收到警告。

        【讨论】:

          猜你喜欢
          • 2012-10-19
          • 2018-11-05
          • 2017-04-22
          • 2013-06-07
          • 1970-01-01
          • 2017-07-25
          • 2010-11-10
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多