[SOLVED] Passing 2D array to a function

I am trying to pass a 2D double array and a 1D string array to a function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int main()
{

	const int NUM_COMPANIES = 6;
	const int NUM_QUARTERS = 4;
	void writeData(double[][NUM_COMPANIES], string[], int, int); //function prototype
	string companyNames[NUM_COMPANIES] = { "ABC", "DEF", "GHI", "JKL", "MNO", "###" };
 //declare a one dimensional string array to hold the names of 6 different companies
	double salesData[NUM_QUARTERS][NUM_COMPANIES] =
 //a 2D double array to hold the sales data for the four quarters in a year
	{ { 40000, 50000, 60000, 70000 },
	{ 35000, 45000, 55000, 65000 },
	{ 25000, 26000, 27000, 28000 },
	{ 31000, 32000, 33000, 34000 },
	{ 42000, 43000, 44000, 45000 },
	{ 10000, 20000, 30000, 40000 } };

	writeData(salesData, companyNames, NUM_COMPANIES, NUM_QUARTERS);

	system("pause");
	return 0;


1
2
3
4
void writeData(double salesData[][NUM_COMPANIES], string companyNames, int NUM_COMPANIES, int NUM_QUARTERS)  //In Main, call a function WriteData
{ 
//...
	}

The issue is that when when I say void writeData(double salesData[][NUM_COMPANIES] it tells me that NUM_COMPANIES is unidentified. Why didn't it get passed to the function from main?
Last edited on
That's because NUM_COMPANIES is local scope within main. It can't be seen outside of main. Move line 4 to before line 1.
Typically when dealing with fixed-size arrays it is a good idea to typedef them.

1
2
3
4
5
6
7
8
9
typedef double SalesData[ 4 ][ 7 ];

void writeData( SalesData salesData, ... );

SalesData salesData = 
{
  {...},
  ...
};

Keep in mind that you have ordered the dimensions in an inconvenient way. What if you want to deal with more companies? (There will always be four quarters.)

1
2
3
4
5
6
typedef double QuarterlyData[ 4 ];

void writeData( QuarterlyData companySales[], int num_companies, ... );

const int NUM_COMPANIES = 8;
QuarterlyData sales[ NUM_COMPANIES ] = ...

This of course makes adding companies at runtime easier:

1
2
3
4
5
6
7
8
9
10
11
12
13
QuarterlyData sales[ 100 ]; // maximum of 100 companies
int num_companies = 0;

// add a company:
sales[ num_companies ][ 0 ] = ...
sales[ num_companies ][ 1 ] = ...
...
companyNames[ num_companies ] = ...
num_companies += 1;

// add a company using a function that sets an argument QuarterlyData
void set_company_sales( QuarterlyData quarterlyData );
set_company_sales( sales[ num_companies++ ] );

Hope this helps.
Topic archived. No new replies allowed.