printing three dimensional array

Hello, I am attempting to print a three dimensional array, the expected format would be cutting slices off the height and showing numbers on the x-y planes. But I got errors in the following code: arg and murray missing subscript, and too many initializes. I thought the array elements can be left empty in a function because it is local array. Can someone help to explain? Thanks!

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

using namespace std;


void multi (int arg[][][], int width, int length, int height)
{
	for (int z = 0; z < height; z++)
	{
		for (int x = 0; x < width; x++)
		{
			for (int y = 0; y < length; y++)
			{
				cout << arg[x][y][z] << ' ';
			}
			cout << endl;
		}
		cout << endl;
	}
}


int main()
{
	int murray[][][] = 
	{
		{{0,1,2,3}, {4,5,6,7}, {8,9,10,11}},
		{{12,13,14,15}, {16,17,18,19}, {20,21,22,23}}
	};

	multi(murray,2,3,4);
	cin.get();
}
The error I get from g++ might shed some light:
7:25: error: declaration of 'arg' as multidimensional array must have bounds for all dimensions except the first


Basically: You can't declare or pass a multi-dimensional array like that. You have to pass and declare the inner dimension sizes explicitly.

https://stackoverflow.com/questions/22346426/omitting-sizes-while-initializing-c-c-multidimensional-arrays

int arg[][3][4]

1
2
3
4
5
	int murray[][3][4] = 
	{
		{{0,1,2,3}, {4,5,6,7}, {8,9,10,11}},
		{{12,13,14,15}, {16,17,18,19}, {20,21,22,23}}
	};
which is a solid argument for using nested vectors or indexed single dimensional data.
http://www.cplusplus.com/forum/general/49079/#msg266703

The code in the link only cares about two dimensions, but the same logic applies: use a templated function to pass the flattened array to the working function with the correct dimensions, and calculate the linear offset using those values.

It might be helpful to have a helper function to compute offsets into the flattened array:

1
2
3
4
5
6
// x ::= outermost dimension
// z ::= innermost dimension
int mda_offset( int xs, int ys, int zs, int x, int y, int z )
{
  return (x * ys * zs) + (y * zs) + z;
}

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