Return of Bidimensional Array not work!

Hi everybody!

I'm new in C++ and this language has some aspects for understand is a bit hard. One of these is the bidimensional array.

I am trying to return one bidimensional array in a function of some Class but I am not getting. Follow the code bellow, someone can help me?


1
2
3
 Scenery env;
 char **arrayEnv;
 arrayEnv = env.buildEnvironment();


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
char** Scenery::buildEnvironment(){

	char environment[10][10] = {
	{'1','1','1','1','1','1','1','1','1','1'},
	{'1','0','0','0','0','0','0','0','0','1'},
	{'1','0','0','0','0','0','0','0','0','1'},
	{'1','0','0','0','0','0','0','0','0','1'},
	{'1','0','0','0','0','0','0','0','0','1'},
	{'1','0','0','0','0','0','0','0','0','1'},
	{'1','0','0','0','0','0','0','0','0','1'},
	{'1','0','0','0','0','0','0','0','0','1'},
	{'1','0','0','0','0','0','0','0','0','1'},
	{'1','0','0','0','0','0','0','0','0','1'}
	};

	return **environment;
	
}
Last edited on
1. This char** is a pointer to a pointer and not an array so you have the wrong type.
2. Your 'environment' is a local array that won't be valid outside of buildEnvironment().

To solve the problem make it a 1d array and at least static.

Look at this http://www.cplusplus.com/articles/G8hv0pDG/ -> Killing MD: 1D Mimics
Why dont you do something like this:

1
2
3
Scenery env;
char (*arrayEnv)[10];
arrayEnv = (char(*)[10])env.buildEnvironment();


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
char* Scenery::buildEnvironment(){

	static char environment[10][10] = {
	{'1','1','1','1','1','1','1','1','1','1'},
	{'1','0','0','0','0','0','0','0','0','1'},
	{'1','0','0','0','0','0','0','0','0','1'},
	{'1','0','0','0','0','0','0','0','0','1'},
	{'1','0','0','0','0','0','0','0','0','1'},
	{'1','0','0','0','0','0','0','0','0','1'},
	{'1','0','0','0','0','0','0','0','0','1'},
	{'1','0','0','0','0','0','0','0','0','1'},
	{'1','0','0','0','0','0','0','0','0','1'},
	{'1','0','0','0','0','0','0','0','0','1'}
	};

	return (char *)environment;	
}


I declared environment as a static variable so the pointer to it will be valid outside of the function buildEnvironment(). This is a strange way of using local variables.

Please tel me know if it works.


Topic archived. No new replies allowed.