dynamic memory allocation issues
Jan 22, 2008 at 6:20pm UTC
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?
Jan 22, 2008 at 6:55pm UTC
Jan 23, 2008 at 9:38am UTC
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 Jan 23, 2008 at 9:38am UTC
Topic archived. No new replies allowed.