簡體   English   中英

C ++將2D數組傳遞給函數時出錯?

[英]C++ Error passing a 2D array to function?

編輯: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;
}

錯誤:“錯誤:']'標記之前的預期主表達式”我需要從文件中獲取數據並將其存儲在2d數組中。 順便說一句,這是一項家庭作業

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

調用getData()時,應在不指定尺寸的情況下傳遞數組。 在聲明列表[X] [Y]之后,將訪問X行Y列中的單個元素。

getData(inFile, list, row);

另外,建議僅對宏使用UPPERCASE,而不對函數參數使用:

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

您可以在聲明和定義函數時提及列大小的最大大小,並且通常將數組的基地址傳遞給函數

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

將它作為帶有行和列信息的雙指針傳遞會更容易。 所以你的代碼是

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

函數定義將保持不變

 getData(inFile, list, row, col);

是使用它的方式。

暫無
暫無

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

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