kiriloff
kiriloff

Reputation: 26333

C++ simple array creation with user given length

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.

Upvotes: 0

Views: 319

Answers (4)

Some programmer dude
Some programmer dude

Reputation: 409442

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.

Upvotes: 0

Steve Townsend
Steve Townsend

Reputation: 54178

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

Upvotes: 0

laurent
laurent

Reputation: 90863

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]);

Upvotes: 5

Dervall
Dervall

Reputation: 5744

Use the new operator.

float r = new float[m_N];

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

delete[] r;

Upvotes: 0

Related Questions