0

How to create one array in a method with user given length? I would like to fill in a vector with user given length with random numbers.

 double* Random::quasiRandomUnif(float a, float b, int NN) 
 {
     int i, errcode;

          N_=NN; // here initialize the member N_

          float r[N_];

     VSLStreamStatePtr stream;
     int i, errcode;

     errcode = vslNewStream( &stream, BRNG,  SEED );
     errcode = vsRngUniform( METHOD, stream, N_, r, a, b );

     double* rd = new double[m_N];
     for(int i=0;i<m_N;i++)
         rd[i]=(double)r[i];

     errcode = vslDeleteStream( &stream );

     return rd;
  }

I thought of N_ a member for the class Random, to be initialized in this function's body, with some user given value -- not possible, since space allocated in array should be a constant. How to deal with?

Kind regards.

2
  • If m_N is not known at compile time then you should allocate r as you did for rd. Remember to delete them or use them with auto_ptr. Commented Apr 19, 2012 at 14:15
  • @PaoloBrandoli You can't store a dynamically allocated array in an auto_ptr - that would be undefined behaviour when the auto_ptr is destroyed, since it'll call delete instead of delete []. std::vector is the way forward here Commented Apr 19, 2012 at 14:18

4 Answers 4

5

In C++, you should use the vector class:

std::vector<double> rd;
for(int i=0;i<m_N;i++) rd.push_back(r[i]);
Sign up to request clarification or add additional context in comments.

Comments

0

Use the new operator.

float r = new float[m_N];

Remember to delete it, when you are done with it.

delete[] r;

Comments

0

Try Boost.ScopedArray. Simpler semantics than vector without the memory management overhead of your own raw array.

Comments

0

I guess the problem is with the r array? Why not allocate that with new as well? Then you can use any expression you like as the size.

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.