簡體   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