0

I'm having a stack overflow allocating a huge matrix on the stack (and I agree with that: it's stupid to allocate it there) and I'm writing the following code since I want to access the matrix's elements with the subscripts indices mat[x][y]

double (*mul1)[N][N];
mul1 = new double[N][N];

I'm receiving an error:

error C2440: '=' : cannot convert from 'double (*)[1000]' to 'double(*)[1000][1000]'

Why can't I allocate a bidimensional array with new?

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
Johnny Pauling
  • 12,701
  • 18
  • 65
  • 108
  • This is actually slightly different from the question someone linked as duplicate, because (I assume) N is known at compile time. You can do it with `double (*mul1)[N];` and you avoid the pointer indirection that appears in the linked question for the nested arrays. (The key is that the `*` _replaces_ one of the `[]`, and `new T[]` returns a pointer to the first element.) Or you can write `unique_ptr mul1(new double[N][N]);` and get automatic cleanup. – entheh Mar 23 '13 at 11:28

2 Answers2

2

You can do it like so:

int N = 10 ;
double** mul1 = new double*[N];
for(int i = 0; i < N; ++i)
   mul1[i] = new double[N];
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
1
double *mul1[N];
for (int i=0;i<N;++i)
    mul1[i] = new double[N];

Representing a 2D array as a 1D array

Performance of 2-dimensional array vs 1-dimensional array

Community
  • 1
  • 1
0x90
  • 39,472
  • 36
  • 165
  • 245