dynamic arrays

Mar 5, 2015 at 2:08pm
Hey guys, I know what the problem is here, but my question is. Is there a way around this, without using a constant too set the size.

1
2
3
4
5
6
7
  int max_rows = 0;
	int max_cols = 0;
	std::cout << "Enter number of rows:  ";
	std::cin >> max_rows;
	std::cout << "\nEnter number of columns:  ";
	std::cin >> max_cols;
	int *numbers = new int[max_rows][max_cols];
Mar 5, 2015 at 2:18pm
no, size of an array must be known at compile time.

better approach would be to use for loop to create 2D arrays on runtime, the size ( for loop parameters) will depend on user input.
Mar 5, 2015 at 2:18pm
You cannot dynamically allocate MD arrays where dimension aside first is not known in compile time. What you can is to allocate array of pointers: int** numbers = new int*[max_rows]; and then allocate array of ints to each pointer:
1
2
for(int i = 0; i < max_rows; ++i)
    numbers[i] = new int[max_cols];


However such nested new is dangerous: leaks, double delete, and other problems could happen when you will use this code carelesly.
http://www.cplusplus.com/forum/articles/17108/
Mar 5, 2015 at 2:23pm
could you give me an example please mate.
Mar 5, 2015 at 2:45pm
Here is an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
	int*** my2Darray = new int**[max_rows];

	// create
	for (int rows = 0; rows < max_rows; ++rows)
	{
		my2Darray[rows] = new int*[max_cols];
		for (int cols = 0; cols < max_cols; ++cols)
			my2Darray[rows][cols] = new int;
	}

	// delete
	for (int rows = 0; rows < max_rows; ++rows)
		for (int cols = 0; cols < max_cols; ++cols)
			delete my2Darray[rows][cols];

        delete[] my2Darray;
Last edited on Mar 5, 2015 at 2:46pm
Topic archived. No new replies allowed.