C ++错误将2D数组传递给函数?

时间:2014-11-21 02:03:39

标签: c++ arrays 2d

编辑:ROW和COLUMN是int值,ROW = 12,COLUMN = 2

int main() {
   double list[ROW][COLUMN];

   ifstream inFile;
   getValidDataFile(inFile);
   cout << "Temperature Data for the year " << getYear(inFile) << endl;

   getData(inFile, list[][COLUMN], ROW); // Error Line


   return 0;
}

错误:&#34;错误:在&#39;]&#39;之前预期的主要表达式令牌&#34; 我需要从文件中获取数据并将其存储在二维数组中。 顺便说一句,这是一项家庭作业

void getData(ifstream& fin, double a[][COLUMN], int ROW) {
    int row, col;
    double num;
    for(row = 0; row < ROW; row++) {
        for(col = 0; col < COLUMN; col++) {
            fin >> num;
            a[row][col] = num;
        }
    }
}

3 个答案:

答案 0 :(得分:2)

当你调用getData()时,你应该传入数组而不指定维度。声明列表[X] [Y]将访问行X列Y中的单个元素。

getData(inFile, list, row);

此外,建议仅对宏使用大写,而不是函数参数:

void getData(ifstream& fin, double a[][COLUMN], int input_row) {

答案 1 :(得分:0)

您可以在声明和定义函数时提及列大小的最大大小,并且像往常一样将数组的基址传递给函数

void print(int p_arr[][10]); //max size of the column   -- declaration
int g_row,g_column;//make it as these variables as global;
int main()
{
   int l_arr[10][10];//local array
   printf("Enter row value and column value");
   scanf("%d%d",&g_row,&g_column);
   for(int i=0;i<g_row;i++)
   {
      for(int j=0;j<g_column;j++)
      {
         scanf("%d",&l_arr[i][j]);
      }
   }
   print(l_arr);//you just pass the array address to the function
   return 0;
}
void print(int p_arr[][10])
{
   for(int i=0;i<g_row;i++)
   {
      for(int j=0;j<g_column;j++)
      {
         printf("%d\t",p_arr[i][j]);
      }
      printf("\n");
   }
   return;
}

答案 2 :(得分:-2)

将它作为带有行和列信息的双指针传递会更容易。所以你的代码将是

void getData(ifstream *fin, double** a, int row, int col); 

函数定义将保持不变

 getData(inFile, list, row, col);

是使用它的方式。

相关问题