簡體   English   中英

將結構的2D數組傳遞給函數

[英]passing 2D array of structure to a function

這是我的結構結構查找

{
   char action;
   int state;
};

行和列的值是已知的,但它們是從文件中讀取的。

main()   
{
   // other initialization...then
   lookup* table[rows][columns];
   for (int i = 0; i < rows;i++)
   {    
        for (int j = 0; j < columns;j++)
        {   
             table[i][j]=new (lookup);
        }
   }
}

然后我將值分配給表的每個元素,現在我想將此表傳遞給另一個函數以進行進一步的操作,例如,

void output(lookup* table)
{
     // print values stored in table 
}

我如何將表及其所有內容從main()傳遞到output()函數? 感謝幫助..

將參數聲明為雙指針(假設您收到一維指針數組)。 由於此類數組連續位於內存中,因此您可以計算當前元素的位置。

void output(lookup** table, int rows, int cols)
{
  lookup* current_lookup = NULL;
  for (int i = 0; i < rows; i++)
  {   
    for (int j = 0; j < cols; j++)
    {
      current_lookup = table[i*cols + j];
      printf("Action: %c, state: %d\n", current_lookup->action, current_lookup->state);
    }
  }
}

您可以通過傳遞數組的第一個元素來調用它:

int main()   
{
   lookup* table[rows][columns];

   //....

   output(table[0]);
   return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM