Refrencing to make 2D array of variable size

Am having trouble getting my references to change the size values of an array.

The goal is to accept a user input and use that to assign a size to my array (with the eventual aim of being able to output shapes of a size input by a user, within an array)

Sorry if any of my lingo's off or I haven't provided enough info, newbie! I've attached the entirety of my code to hopefully minimize confusion!

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

using namespace std;

int main ()
{

	int size;

	cout << "Please enter the size of your diamond: ";
	cin >> size;
	cout << endl;

	int center = size;
	int rowStart = 0;
	int rowEnd = rowStart + (center - 1);
	int rowMid = rowStart + (center/2);
	int colStart = rowMid;
	int colEnd = colStart+1;

	char display [1][1];
	{
	char* display [1][1] = new char[size][size]; /* this line */
                                                     /* causes problems? */

		for(int r = rowStart; r < rowMid; r++ )
		{
			for(int c = colStart; c < colEnd ; c++)
			{
				display[r][c] = '*';
			}

			colStart--;
			colEnd++;
		}
	}
}


I hope this shows what i'm trying to achieve here!
Just gonna start by pointing out some lines that need deleted:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
	char display [1][1];  // not sure why this exists
	{ // what's this for?
	char* display [1][1] = new char[size][size]; /* this line */
                                                     /* causes problems? */

		for(int r = rowStart; r < rowMid; r++ )
		{
			for(int c = colStart; c < colEnd ; c++)
			{
				display[r][c] = '*';
			}

			colStart--;
			colEnd++;
		}
	} // what's this for?
} 


Now as for dynamically allocating a 2D array, it's possible but you should really use a vector if you know what those are. Here's how to allocate a 2D character array:

1
2
3
char** display = new char*[size]; //declare a pointer to a char pointer
for (int i = 0; i < size; i++)             //loop through this array
          display[i] = new char[size];//each index becomes a new char array 


After that you can use display like a normal 2D array, like display[i][k] or whatever you want to do. Be sure to delete all the allocated memory when you're done though (you'll need to loop through the array again).
Topic archived. No new replies allowed.