Initializing 2d array with variables

How do I declare this array?

char array[rows][cols];

The user needs to be able to specify the number of rows and columns. I'm not having much luck searching around.

Thanks
you're going to have problems using an array for that since an array's memory is allocated at compile time. you'll never be able to allow a user to dynamically allocate the size of an array unless you use some type of dynamic structure like a linked list or a flex array or something similar
You can dynamically allocate the size of an array with new. You'll need to use a loop to do the higher dimensions, though.
How would I go about that?
remember the goto x,y jeff..

x is going to the right or left, while the y is going up or down.


x<------------------>x


y
/\
l
l
l
l
l
\/
y


x,y

x is the cols, and y is the rows.


try ask for the user how many cols and store it to a variable called cols, then create another one ask for rows and store it to a variable called rows. you can have your array[cols][rows]..
Last edited on
If I want to create a 2d array with variable column/row size I usually do it like this:

1
2
3
4
5
6
7
8
9
10
11
12
char * myarray;

int main () {
    // do something to get my row and column values here

    myarray = new char [row*col];

    // now let's say I want to access row 5, column 6 (0 being the first, not 1);

    char row_5_col_6 = myarray[row*5+6];
    return 0;
}


I don't know if this is conventional or not, but it does work...
Well this will compile but not run;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int main()
{
	int cols = 10;
	int rows = 10;
	char **myArray;
	 myArray = new char*[rows];
	 myArray[rows] = new char[cols];

	 for( int i = 0; i < rows; i++ )
	 {
		 for ( int j = 0; j < cols; j++ )
		 {
			 myArray[i][j] = 'X';
		 }
	 }
	 for( int i = 0; i < rows; i++ )
	 {
		 for ( int j = 0; j < cols; j++ )
		 {
			 cout << myArray[i][j];
		 }
	 }
}

It does that thing where it says the program has stopped working.
1
2
myArray = new char*[rows];
myArray[rows] = new char[cols];

First thing wrong with this is there are 10 rows (so indexes 0 through 9) and the second line is indexing 10, which is an array out of bounds.

What you need to do is initialize each row (myArray[0] through myArray[9]) with new. So, each row is a char array of size cols. You need to initialize this in a loop. Remember you need a matching delete [] when you're done with the arrays for each call to new[].
Last edited on
Ha! I love this forum. Thanks shacktar.
Topic archived. No new replies allowed.