1

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;
    }
}
1
  • A 2D jagged array with dimensions determined at runtime that doesn't leak: std::vector<std::vector<float>>. Commented Dec 25, 2011 at 11:49

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

What is wrong?

You're not using std::vector (that's one of the things that's wrong, @FredO covered the other thing).

#include <vector>

int main(){
  typedef std::vector<float> inner_vec;
  typedef std::vector<inner_vec> outer_vec;

  int pop = 50, d = 12;
  // first parameter to vector is its size
  // second is what every element should be initialized to
  outer_vec uye(pop, inner_vec(d));
  for(unsigned n = 0; n < uye.size(); ++n){
    for(unsigned m = 0; m < uye[n].size(); ++m){
      uye[n][m] = (float)n*m;
    }
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.