Dynamic 2d Array

Im working on a connect 4 game assignment using a dynamic 2d array. This double pointer stuff is causing me much pain. I think I'm close. I can't figure out how to pass the GameBoard to the display function. Currently nothing in the array. Any help would be awesome. 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
35
36
#include <iostream>

using namespace std;

int getConnections(){
	int size;
		cout << "How many connections to win [3, 4, 5, or 6]?\n";
		cin >> size;
	while(size<3 || size>6){
		cout << "Invalid selection.[3, 4, 5, or 6]?\n";
		cin >> size;}
	return size;
}
char buildGameBoard(int winsize){
	int x = winsize + 2;
	int y = winsize + 3;
	char **GameBoard = new char *[x];
	for(int i=0;i<x;i++)
    GameBoard[i] = new char[y];
	return **GameBoard;
}
void displayGameBoard(char **GameBoard, int winsize){
	for(int i=0; i<winsize+2; i++){
		for(int j=0; j<winsize+3; j++){
		cout << GameBoard[i][j]  << " ";}
		cout << endl;
	}
	return;
}

int main(){
	int winsize = getConnections();
	char **GameBoard = buildGameBoard(winsize);
	displayGameBoard(GameBoard, winsize);
	return 0;
}

I know. It's a work in progress. I'm new to programming.
You are very close:

char buildGameBoard(int winsize){

the 'char' here means that buildGameBoard returns a singular char. This is not what you want. Since you want it to return a 2D array represented by a pointer to a pointer, you would want it to return a pointer to a pointer... ie:

char** buildGameBoard(int winsize){

Now it'll actually return the 2D array as you intend.


Furthermore, when you actually return the array:

return **GameBoard;

GameBoard is a char**, so by doing **GameBoard, that is effectively the same as doing GameBoard[0][0]. That is, you are only returning the first character in the array. Again, this is not what you want. you want to return the actual pointer to the array. So just change that to this:

return GameBoard;



The only other problem that I see is that you are not doing a delete[] on the stuff you are new[]'ing. It's not a big deal for this small program, but it's something you should get in the habit of: every new[] should have a matching delete[].
Ahh thank you sir. Fixed my problem. And thanks for the delete advise. Ill add a function to fix the memory leak.
Topic archived. No new replies allowed.