Search code examples
c++multidimensional-arraydynamic-memory-allocation

Dynamic 2D Array Initialization


I want to create and initialize a 2D array but the initialization is failed. I encounter "The program has unexpectedly finished." in Qt Creator.

What is wrong?

in .h file

private:
    int pop;
    int d;
    float **uye;

in .cpp file

pop=50;
d=12;
uye = new float*[pop];
for(int i=0; i<d; i++) uye[i] = new float[d];

for(int n=0; n<pop; n++)
{
    for(int m=0; m<d; m++)
    {
        uye[n][m] = (float) n*m;
    }
}

Solution

  • The first loop for(int i=0; i<d; i++) should probably be for(int i=0; i<pop; i++). Otherwise, you are only reserving space for 12 elements, but later try to access 50.

    Note that having raw pointer members is considered a very bad idea in modern C++, because you need to worry about copying semantics. Better use a flat std::vector<float> and do the 2D to 1D mapping manually, or use a std::vector<std::vector<float> > with convenient access syntax.

    I would prefer the second version. Without seeing more context:

    pop = 50;
    d = 12;
    uye = std::vector<std::vector<float> >(pop, std::vector<float>(d));
    

    The nested for loops that follow work exactly the same, no changes required.