returning a pointer to pointer to pointer from function

Hi guys,
I am trying to return dynamically allocated 3-dimensional array from the function. When I run the code, it does not give an error message in the error window. But after the console opens, it gives an error like: program.exe has stopped working.
windows can check online for a solution to the problem.

In the main function I return the function like this:

int ***array = threeDimensionalArray();

after the return, i output the 3 dimensional array and then delete it.

in the function part, i created a dynamically allocated 3 dimensional array and then fill the array with numbers and then return it like this:

return p_p_p_Array;

Any help will be appreciated. Thank you.


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
 #include <iostream>
#include <string>
 
using namespace std;

 
	int  ***threeDimensionalArray ()
{
	//allocate a three dimensional 3x2x4 array of ints
	int ***p_p_p_Array = new int**[3];

	for (int i=0; i<3; i++)
	{
		p_p_p_Array[i] = new int* [2];
		for (int j=0; j<2; j++)
		{
			p_p_p_Array[i][j] = new int [4];
		}

	}


	//fill the array
	for(int i=0; i<3; i++)
	{
		for (int j=0; j<2; j++)
		{
			for (int k=0;j<4; k++)
			{
				p_p_p_Array[i][j][k] = i+j+k;
			}

		}

	}

	 
	return p_p_p_Array;
}


int main()
{
		int ***array  = threeDimensionalArray();		//call the function

		//outpout the array
	for(int i=0; i<3; i++)
	{
		for (int j=0; j<2; j++)
		{
			for (int k=0; k<4; k++)
			{
				 cout << array[i][j][k] << " " ;
			}
			cout << endl;
		}
		cout << endl;
	}

	//deallocate the 3D array
	for (int i=0; i<3; i++)
	{
		for (int j=0; j<2; j++)
		{
			delete [] array[i][j];
		}
		delete [] array[i];

	}
	delete [] array;


	system("pause");
	return 0;
}
$ valgrind ./test
...
==52808== Invalid write of size 4
==52808==    at 0x400A93: threeDimensionalArray() (test.cc:30)
==52808==    by 0x400ADD: main (test.cc:44)


looking just above that line 30, I see

for (int k=0;j<4; k++)

did you mean for (int k=0;k<4; k++) ?
oh, thank you Cubbi.

You're right. I mistyped line 30. it should have been for (int k=0;k<4; k++)

Now it works fine.
Topic archived. No new replies allowed.