dynamic memory allocation issues

Greetings,

I am working on a problem where I want to use dynamic memory allocation to specify a mulidimentional array.

I try using this code:

1
2
3
4
 
int i;
int *ptr;
ptr = new(nothrow) int [i][i]; 


yet when I try to compile, it references the third line above and says:
`i' cannot appear in a constant-expression.

Can I not use dynamic memory allocation while using multidimensional arrays?
Try it with a regular array - as the cplusplus.com tutorial on arrays will tell you, there's really no such thing (in terms of memory, anyway) as a multidimensional array.

http://www.cplusplus.com/doc/tutorial/arrays.html#multidimensional_arrays
i think you need this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream.h>

void main() {
	const int rows = 4;
	const int cols = 4;

	// declaration
	int ** a;

	// allocation
	a = new int*[rows];
	for(int i = 0; i < rows; i++)
		a[i] = new int[cols];

	// initialization
	for(int j = 0; j < rows; j++)
		for(int i = 0; i < rows; i++)
			a[i][j] = 0;
}


I hope this helps you
Last edited on
Topic archived. No new replies allowed.