Passing a 2D Array by ref

I am trying to pass a 2d array to a function by reference and for some reason it is not giving me a correct output (step 3 in the code below). I am super new to C++ so please be kind :(

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>
#include<string>

using namespace std;

//function to increment the value of array elements by 1
void readarr (int (*arr)[2][3])
{
	
	for(int i=0;i<2;i++)
		for(int j=0;j<3;j++)
			cout<<(*arr)[i][j]+1<<"|";
}


int main()
{
	int arr[2][3]={{1,5,3},
				   {6,4,2}};

	//step1: initial array
	for(int i=0;i<2;i++)
		for(int j=0;j<3;j++)
			cout<<arr[i][j]<<"|";

	cout<<endl;

	//step2: function to modify
	readarr(&arr); 

	cout<<endl;

	//step3: modiefied array?????still returning step 1
	for(int i=0;i<2;i++)
	for(int j=0;j<3;j++)
		cout<<arr[i][j]<<"|";

	cin.get();

	return 0;

}
Last edited on
Whenever you pass a array into a function, it automatically assumes it is passed by reference. That is what I learned in my new programming class 2 months ago lol.
Thanks Hunter.But in step 3 when I am trying to print out the modified array it is not doing so..

My understanding was By Reference means that it passes the address(not a copy) of the array so when we make changes within the function it would make changes to the original array as well..so confusing :/

Your readarr function isn't changing the actual value in the array. It just outputs the current value + 1.

Hi wildblue..so what would I need to change in the code to modify the original array..??
You need an assignment statement. Just think how you'd do this with any variable you wanted to add 1 to, it's the same idea. a = a + 1, or a += 1 changes the value in a by adding 1.

There's a bit on passing arrays in functions on this site here - scroll down a bit to Arrays as Parameters.
http://www.cplusplus.com/doc/tutorial/arrays/
To modify elements in the array, you have to modify elements in the array. Normally this is done via some sort of assignment.

For instance if I have an int, i with value 1 and I want to increment it by 2 so that it's value is 3, I might write: i += 2, but if I were to just write, instead: cout << i+2; the number output would be 3, but i would be unchanged. There was no assignment to it.
Last edited on
OHHH..ill try this and get back :D Thankkk you all so much..
That Worked :D :D Thank you Thank you !
Topic archived. No new replies allowed.