c++ - how do I allocate one block of memory with new? -


i have 2 dimensional array i've allocated dynamically using new.

the problem want allocate memory 1 connected block instead of in separated pieces increase processing speed.

does know if it's possible new, or have use malloc?

here's code:

a = new double*[m];     (int i=0;i<m;i++)     {         a[i]= new double[n];     } 

this code causes segmentation fault

phi = new double**[xlength]; phi[0] = new double*[xlength*ylength]; phi[0][0] = new double[xlength*ylength*tlength]; (int i=0;i<xlength;i++) {     (int j=0;j<ylength;j++)     {         phi[i][j] = phi[0][0] + (ylength*i+j)*tlength;     }     phi[i] = phi[0] + ylength*i; } 

you can allocate 1 big block , use appropriately, this:

double* = new double[m*n]; (int i=0; i<m; i++) {     (int j=0; j<n; j++) {         a[i*n+j] = <my_value>;     } } 

instead of using new, can use malloc - there no difference, except new must released delete, , malloc() released free().

update1: can create "true" 2d array follows:

double** = new double*[m]; double*  b = new double[m*n]; (int i=0; i<m; i++) {     a[i] = b + n*i; } (int i=0; i<m; i++) {     (int j=0; j<n; j++) {         a[i][j] = <my_value>;     } } 

just sure release both a , b in end.

update2:

by popular request, how can create "true" 3-dimensional array (with dimensions m x n x o):

double*** = new double**[m]; double**  b = new double*[m*n]; double*   c = new double[m*n*o]; (int i=0; i<m; i++) {     (int j=0; j<n; j++) {         b[n*i+j] = c + (n*i+j)*o;     }     a[i] = b + n*i; } (int i=0; i<m; i++) {     (int j=0; j<n; j++) {         (int k=0; k<o; k++) {             a[i][j][k] = <my_value>;         }     } } 

this uses 2 relatively small "index" arrays a , b, , data array c. usual, 3 should released after use.

extending more dimensions left exercise reader.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -