Cannot print 3D array using function

I can’t print 3d array by using the following function.
Is there something I am misunderstanding?

#include <iostream>

using namespace std;

void printArray(int arrayName[], int row, int column);

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

printArray(apple, 3, 3);
}

void printArray(int arrayName[], int row, int column){
for(int x = 0; x < row; x++){
for(int y = 0; y < column; y++){
cout << minnie[x][y] << " ";
}
cout << endl;
}
}

yes.
first, is 2-d array...

second, you have 1-d in the print function.

third, there is no such thing as minnie.

void main is nonstandard and not recommended. use int main for standard compliance.
Last edited on
This problem is an example of the dreaded C-style (2 dimensions only) array. You need to hard code the number of columns, let the number of rows to count themselves and then, without pointers, pass the array to the function without changing its name to 'minnie' without indicating how and why.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

using namespace std;

void printArray(int[][3], int, int);

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

void printArray(int arrayName[][3], int row, int column)
{
    for(int x = 0; x < row; x++)
    {
        for(int y = 0; y < column; y++)
        {
            cout << arrayName[x][y] << " ";
        }
        cout << endl;
    }
}



1 2 3 
4 5 6 
Program ended with exit code: 0


https://stackoverflow.com/questions/8767166/passing-a-2d-array-to-a-c-function
It helps a lot! Thank you very much!
You can also do it using a using (or a typedef) like this:

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

using namespace std;

const size_t ROW {3};
const size_t COL {3};

using Array = int[ROW][COL];

void printArray(Array, int);

int main()
{
	Array apple = {{1,2,3}, {4,5,6}};
	printArray(apple, 2);
}

void printArray(Array arrayName, int row)
{
	for (int x = 0; x < row; ++x) {
		for (int y = 0; y < COL; ++y)
			cout << arrayName[x][y] << " ";

		cout << endl;
	}
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

void printArray(int *, int, int);

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

void printArray(int *a, int row, int column)
{
    for(int e = 0; e < row * column; e++) cout << a[e] << ( (e+1) % column ? " " : "\n" );
}


1 2 3
4 5 6
Topic archived. No new replies allowed.