1

In this program, I am trying to read a file into a function with 2 parameters, a one-dimensional array and a two-dimensional array. The problem I'm having is that I keep getting this error.

main.cpp: In function ‘int main()’: main.cpp:23:48: error: cannot convert ‘double (*)[3]’ to ‘double**’ for argument ‘2’ to ‘void printFile(std::__cxx11::string, double**)’ printFile(Name[NUM_OF_ROWS], HoursPaySalary);

I have tried for a long time to understand how to fix this problem, and even though I have the exact error code, I still can't figure out what to do. I know you have to pass arrays as a reference to function parameters, but I'm having trouble understanding how to do that with my 2d array.

Here is the code I have so far:

#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>

using namespace std;

// Global Variables
const int NUM_OF_ROWS = 10;
const int NUM_OF_COLUMNS = 3;



// Function prototypes
void printFile(string Name, double* HoursPaySalary[NUM_OF_COLUMNS]);


int main() {
    // Main starts here
    string Name[NUM_OF_ROWS];
    double HoursPaySalary[NUM_OF_ROWS][NUM_OF_COLUMNS];

    printFile(Name[NUM_OF_ROWS], HoursPaySalary);


    return 0;
}

void printFile(string Name[], double HoursPaySalary[][NUM_OF_COLUMNS]) {
  ifstream dataFile;
  dataFile.open("ch8_Ex17Data.txt");
  
  while (!dataFile.eof()) {
    for (int i = 0; i < 10; i++) {
      dataFile >> Name[i] >> HoursPaySalary[i][i + 1] >> HoursPaySalary[i][i + 2];
      cout << Name[i] << " " << HoursPaySalary[i][i+1] << HoursPaySalary[i][i+2];
    }
  }



  dataFile.close();

}


Thanks guys!

  • 1
    Does this answer your question? [Passing a 2D array to a C++ function](https://stackoverflow.com/questions/8767166/passing-a-2d-array-to-a-c-function) – Silidrone Feb 06 '21 at 10:00
  • @ πάντα ῥεῖ: A link to a duplicate having an WRONG accepted answer with 444 upvotes. That is misleading. There is a defined way in C++, how to pass 2d arrays to functions. Give both dimensions and pass by reference or pointer. Reference: ````int (&array)[ROWS][COLS]````. Pointer: ````int (*array)[ROWS][COLS]```` – Armin Montigny Feb 06 '21 at 10:48
  • @ArminMontigny Passing a pointer or reference is not the same as passing the object itself. The correct answer (of course) is that it is impossible to pass an array to a function in C++. The duplicate answer that you are saying is wrong, is what almost every beginner who asks this question actually wants to do (including this beginner). So I don't think there is anything misleading here. – john Feb 06 '21 at 12:09
  • So, the question is: "**How** do I pass a 2d array as a parameter to function in c++?" The answer to the **how** is: Via pointer or via reference . . . – Armin Montigny Feb 06 '21 at 13:26

0 Answers0