将结构的 2D 数组传递给函数

passing 2D array of structure to a function

本文关键字:函数 数组 结构 2D      更新时间:2023-10-16

这是我的结构结构查找

{
   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: %dn", current_lookup->action, current_lookup->state);
    }
  }
}

您可以通过传递数组的第一个元素来调用它:

int main()   
{
   lookup* table[rows][columns];
   //....
   output(table[0]);
   return 0;
}