简体   繁体   中英

Creating a dynamic 2D array

I need to have a 2D array of double. Its width is around 900. Its height as well (the same width value).

Dealing with two loops (one for the width and one for the height), I really need to get access to all the pixels of the 900X900 image that I will process.

The size of the array is too big (error when specifying the number of raw and column).

I thought about establishing that with a dynamic array to optimize the time of calculation and to free the memory everytime I deal with one pixel on the two loops.

But I really cannot find the syntax I would like to have to declare a 2D dynamic array (malloc, setting array element values and freeing the memory).

Wrap it in a class:

class Matrix2D {
    typedef std::vector<double> Column;
    std::vector<Column> columns;
public:
    Matrix2D(unsigned int width, unsigned int height) :
    columns(width, Column(height)) {
    }

    double& at(unsigned int i, unsigned int j) {
        return columns[i][j];
    }
};

Matrix2D matrix(900, 900);

matrix.at(45, 65) = 1234.5678;

I need to have a 2D array of double

Since you are using C++ you should use STL classes that will take care of ugly memory management for you. So you are actually looking for std::vector< std::vector<double> > , or for the sake of the readability of your code:

#include <vector>
typedef std::vector<double> DVector;      // row represented by vector of doubles
typedef std::vector<DVector> MyVector;    // 2D array as a vector of these rows

And then avoid using dynamic allocation wherever it's possible to do so. Take advantage of RAII idiom :

{
    MyVectorarr;  // vector object with automatic storage duration
} // <-- vector is automatically destructed when execution goes out of scope

Questions that might help you:
Multi-dimensional vector
Initialization of a vector of vectors?
vector of vector

I associate malloc with pure C, not C++ (as the prior answer points yout, you should use std::vector). However, if you really want to:

// allocate the memory in a block
double* block = (double *) malloc(sizeof(double) * xSize * ySize);
// allocate memory for the accessor array
double* accessor = (double*) malloc(sizeof(double*) * xSize);
// assign memory addresses
double* curPtr = block;
for (int i = 0; i < xSize; ++i) {
    accessor[i] = curPtr;
    curPtr += ySize;
}

// you can now access the array via accessor[x][y]

// now need to free malloced memory:
free(accessor);
free(block);

If you do it this way, I highly suggest tying it to the RAII pattern, otherwise you'll eventually get a memory leak. Using the STL's containers is a better approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM