12

Is there a way in C++ to construct a float array initializing it's values?

For example, i do:

float* new_arr = new float[dimension];
for(unsigned int i = 0; i < dimension; ++i) new_arr[i] = 0;

Is it possible to do the assignment during the contruction?

2 Answers 2

23
float* new_arr = new float[dimension]();
Sign up to request clarification or add additional context in comments.

3 Comments

And with uniform initialization (C++11) you can do new float[dimension]{} or even give values: new float[dimension]{1.f,.5f,1.3f}.
If you are not using C++11 and want to do it, you can probably get away with declaring a static const array somewhere where you store the initial values, and memcpying it over your newly allocated arrays.
@Wug not memcpy, std::copy
11

In this particular case (all zeroes) you can use value initialization:

float* new_arr = new float[dimension]();

Instead of explicitly using new[] you could use a std::vector<float> instead:

std::vector<float> new_vec(dimension, 0);

2 Comments

I'm not free to use the vector template since i'm using some external lib. Thank you.
@Aslan986: if the problem is some function expection a float*, then simply pass &v[0]. a std::vector has guaranteed contiguous buffer. so unless you library is like, multi-processing on graphics card with custom runtime, then just use std::vector.

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.