Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
871 views
in Technique[技术] by (71.8m points)

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

I have a two dimensional array that I've allocated dynamically using new.

The problem is I want to allocate the memory as one connected block instead of in separated pieces to increase processing speed.

Does anyone know if it's possible to do this with new, or do I have to use malloc?

Here's my code:

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

This code causes a segmentation fault

phi = new double**[xlength];
phi[0] = new double*[xlength*ylength];
phi[0][0] = new double[xlength*ylength*tlength];
for (int i=0;i<xlength;i++)
{
    for (int j=0;j<ylength;j++)
    {
        phi[i][j] = phi[0][0] + (ylength*i+j)*tlength;
    }
    phi[i] = phi[0] + ylength*i;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can allocate one big block and use it appropriately, something like this:

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

Instead of using new, you can use malloc - there is no much difference, except that new must be released with delete, and malloc() released with free().

UPDATE1: You can create "true" 2d array as follows:

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

Just be sure to release both A and B in the end.

UPDATE2:

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

double*** A = new double**[m];
double**  B = new double*[m*n];
double*   C = new double[m*n*o];
for (int i=0; i<m; i++) {
    for (int j=0; j<n; j++) {
        B[n*i+j] = C + (n*i+j)*o;
    }
    A[i] = B + n*i;
}
for (int i=0; i<m; i++) {
    for (int j=0; j<n; j++) {
        for (int k=0; k<o; k++) {
            A[i][j][k] = <my_value>;
        }
    }
}

This uses 2 relatively small "index" arrays A and B, and data array C. As usual, all three should be released after use.

Extending this for more dimensions is left as an exercise for the reader.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...