problem passing 2-D array to a function

How to pass 2-d array in a function if the size of the 2d array is read from user input

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
41
42
#include<iostream>
using namespace std;
void Takeinput(int N,int *arr[]){
    int i=0;
    while(i<N){
    for(int j=0;j<N;j++){
        cin>>arr[i][j];}
        i++;
    }
    return ;
}
int Sum(int N,int *arrA[],int *arrB[])
{ int sum =0,sum1=0,sum2=0;
 int i=0;
 while(i<N){
    for(int j=0;j<N;j++){
    sum =sum + arrA[i][j];
    sum1= sum + arrB[i][j];
    }
    sum2 = sum2 + sum*sum1; }
return sum2;
 
}
int main(){
    int N;
    cin>>N;
    int arrA[N][N];
    int arrB[N][N];
    Takeinput(N,arrA);
    Takeinput(N,arrB);
    int Q;
    while(Q--){
        char ch;
        int i,j,k;
        cin>>ch;
        cin>>i>>j>>k;
        if(ch=='A') arrA[i][j] = k;
        else arrB[i][j]= k;
        cout<<Sum(N,arrA,arrB)<<endl;
        }
        return 0;
    }
Last edited on
What you are currently doing is illegal in C++.

In C++ you should use vectors for any dynamic arrays by default
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Example program
#include <iostream>
#include <vector>

// pass the board to a function
void change(std::vector<std::vector<int>>& board)
{
    // board.size() can get outer dimension
    // board[0].size() can get inner dimension (make sure board.size() is not 0 first)
    board[2][0] = 5;
}

int main()
{
    int Size;
    std::cin >> Size;

    // Create a 2D vector (vector of vectors, each of Size size)
    std::vector<std::vector<int>> board( Size, std::vector<int>(Size) );
    
    change(board);  
}


If you must use arrays, use dynamic allocation for your arrays:
See an example at: http://www.cplusplus.com/forum/beginner/240012/

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
// Example program
#include <iostream>

// pass the board to a function
void change(int** board, int size)
{
    board[size-1][size-1] = 5;
}

int main()
{
    int Size;
    std::cin >> Size;
  
    // Create a board (2d array)
    int** board = new int*[Size];
    for (int i = 0; i < Size; i++)
    {
        board[i] = new int[Size];
        for (int j = 0 ; j < Size; j++)
            board[i][j] = 0;
    }

    change(board, Size);  
    std::cout << board[Size-1][Size-1] << "\n";
    
    // delete dynamic memory
    for (int i = 0; i < Size; i++)
    {
        delete[] board[i];
    }
    delete[] board;
}
Last edited on
Hello amiable143,

As Ganado ha pointed out What you are trying to do is illegal in C++. What this means is that you can not define the size of any array at run time except a dynamic array which has its own problems to deal with.

The point is that when the program compiles it needs to know the exact size of the array at compile because it sets aside space on the stack for the array. This can not be done at run time. See the changes I made to your program below. This will compile where as your program does not.

The way I fixed your program is with the use of "MAXSIZE" which gives the array a fixed size to start with and allows the program to compile. Then the value of "n", which should be a lower case letter where as "N" leads me to believe that it is a variable defined as a constant value, is used to use only the part of the array that is needed.

Hint: As you will see in the program I like to use the variable names "MAXROW" and "MAXCOL" as they are more descriptive for what they do. And you only have one place to change the array size if needed.

Passing the array to a function is partially correct, but the second dimension must have a value. So in your use it should look like int *arr[MAXCOL] might work I have not tested this yet. And even int arr[MAXROW][MAXCOL] will most likely degrade to a pointer in the function.

Hint: If I am testing or having a problem with a function I will pass the array by reference as int (&arr)[MAXROW][MAXCOL]. In this case each dimension of the array must have a value. Right now I do not see any need to pass the arrays by reference.

Inside main and the while loop you define variables. "n","q", "i", "j" and "k". All would do better with a more descriptive names. Even though it helps people like me understand the program better now it is more for you in the future when you look back at this program it makes it easier to understand what everything is. In the while loop I changed "i" to "row", "k" to "col" and "k" to "inputValue". I am not saying that there is anything wrong with what you did, but now is the time to learn to do better.

The last three line I added to keep the console window open before the program ends. The line std::cin.ignore(...) is the more preferred way of clearing the input buffer.

One last note: There is nothing wrong with where you have put the opening { brace. To the compiler it does not care, but pressing enter and putting the opening { brace on the next line and the closing } brace in the same column it makes the program easier to read. Also proper indenting keeps everything together. Another advantage is when you have several {}s it makes it easier to find a missing closing } brace when they line up in the same column and proper indenting is used.

There are still some changes I want to make to the program before I test it. I will let you know if I find any problems.

This is what I did to your program to get it to compile.
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include<iostream>
#include <cctype>  // <--- Added.
#include <limits>  // <--- Added.

//using namespace std;  // <--- Best not to use.

//constexpr size_t MAXSIZE{ 100 };
constexpr size_t MAXROW{ 100 };  // <--- Added.
constexpr size_t MAXCOL{ 100 };  // <--- Added.

// <--- Changed the variable "N" to "n". A better name might be "size" or "maxUsed". Something that would describe this variable better for what it is used for.

void Takeinput(int n, int arr[MAXROW][MAXCOL])
{
	int i = 0;
				   // <--- Blank space for readability.
	while (i < n)  // <--- Notice spacing.
	{
		for (int j = 0; j < n; j++)
		{
			// <--- Needs prompt. "j + 1" could be used in the prompt and maybe even "n".
			std::cin >> arr[i][j];
		}
		i++;
	}

	return;  // <--- Not needed for a void return value. The function automatically returns when it reaches the closing }.
}

int Sum(int n, int arrA[MAXROW][MAXCOL], int arrB[MAXROW][MAXCOL])
{
	int sum = 0, sum1 = 0, sum2 = 0;
	int i = 0;

	while (i < n)
	{
		for (int j = 0; j < n; j++)
		{
			sum = sum + arrA[i][j];
			sum1 = sum + arrB[i][j];
		}
		sum2 = sum2 + sum*sum1;
	}
	return sum2;
}

int main()
{
	int n{};  // <--- Initialization not needed, but a good practice.

	int arrA[MAXROW][MAXCOL]{};
	int arrB[MAXROW][MAXCOL]{};

	// <--- Needs prompt to know what to input.
	std::cin >> n;

	Takeinput(n, arrA);
	Takeinput(n, arrB);

	int q{ 1 };  // <--- Need to initialize 'Q' or input a value for 'Q'. Changed to make it compile.

	while (q--)  // <--- As is 'Q' may have a value of "-858993460" or something similar which would never reach zero. Also will not compile because 'Q' has no value other than a garbage value.
	{
		char ch;  // <--- Used to determine which array to use.
		int row, col, inputValue;

		// <--- Needs prompt.
		std::cin >> ch;
		ch = std::toupper(ch);  // <--- Added to make sure "ch" is in upper case. Needs header file "cctype".

		// <--- Needs prompt and example of how to input.
		std::cin >> row >> col >> inputValue;

		if (ch == 'A')  // <--- Better way to write this for readability. {}s are optional for one line, but needed for more than one line.
			arrA[row][col] = inputValue;
		else
			arrB[row][col] = inputValue;

		std::cout << Sum(n, arrA, arrB) << std::endl;
	}

	// The next line may not be needed. If you have to press enter to see the prompt it is not needed.
	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>.
	std::cout << "\n\n Press Enter to continue";
	std::cin.get();

	return 0;
}

Notice the comments in the program.

Any questions let me know.

Hope that helps,

Andy
Thanks a lot sir...it was really helpful...
Topic archived. No new replies allowed.