passing 2d Array to function

Expected primary-expression before ']' token

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include<iostream>
using namespace std;

 
void getInput(int[][2],int);
void netSalary(int[][2],int);
 
main()
{
const int arraySize= 100;
	
/*getInput();
netSalary();
unlucky();
displayOutPut(); */
int sal[arraySize][2];
int lucky[100] = {0};
int numEmps;
cout<<"Please Enter Total Number Of Employees: ";
cin>>numEmps;

getInput(sal[][2],numEmps);			//Calling Function To Get Input
netSalary(sal[][2],numEmps);
}

void getInput(int sal[][2], int numEmps)	//Function To get Input
{
	for(int i = 0; i<numEmps; i++)
	{
		cin>>sal[1][0];
	}
}
You only need to mention the name of the array when passing it to a function.

1
2
getInput(sal, numEmps);
netSalary(sal, numEmps);
void getInput(int sal[][2], int numEmps)


its a lot easier to fix things later if you need 3 or 5 or whatever if you make that 2 a named constant instead of a hard one.

alternately you can use **sal instead, but somehow it needs the dimensions, passed in, part of object, global (prefer, namespaced) constant, etc.


You will see more of this later.
Last edited on
Hello Najam489,

FYI another way of writing your program. I commented the changes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include<iostream>
using namespace std;

const int arraySize = 100;  // <--- Moved here so thet it is availavle to everything.
constexpr int MAXCOL{ 2 };  // <--- Added

void getInput(int[][MAXCOL], int);  // <--- Changed
void netSalary(int[][MACOL], int);  // <--- Changed

main()
{

	/*getInput();
	netSalary();
	unlucky();
	displayOutPut(); */
	int sal[arraySize][MAXCOL];  // <--- Changed
	int lucky[arraySize] = { 0 };  // <--- Changed
	//int lucky[arraySize][MAXCOL]{ 0 };  // <--- Another way to define the array.

	int numEmps;
	cout << "Please Enter Total Number Of Employees: ";
	cin >> numEmps;

	getInput(sal, numEmps);			//Calling Function To Get Input
	netSalary(sal, numEmps);
}

void getInput(int sal[][MAXCOL], int numEmps)	//Function To get Input  <--- Changed
{
	// <--- Nested for loops to deal with the array better. Both loops start at 0.
	for (int i = 0; i < numEmps || i < arraySize; i++)  // <--- || keeps you going past your array bounds.
	{
		for (int j = 0; j < MAXCOL; j++)
		{
			cin >> sal[i][J];

		}
	}
}


Hope that is useful,

Andy
sir i did not get it can you please provide your email, skype, facebook etc any thing where i can contact you
Topic archived. No new replies allowed.