I am creating a char pointer to an array and wanted to initilaize it so that all elements in the array have 0 (in bits). So for example:
char* buffer = new char[bufferSize];
buffer[0] to buffer[bufferSize] will have '00000000' stored in each index. I am trying to store 8 bits of zeros in each cell.
How can i initialize it? I am also supposed to use fill().
So far,
fill(&buffer, &buffer[bufferSize], 0)
doesn't work.
You can use fill, but you must remember it accepts a pair of iterators. A pointer to the array elements is an iterator of the array already. There is no need to take the address of an iterator to pass it, so your first argument is incorrect. The more correct form would be
std::fill(buffer, buffer + bufferSize, 0);
or
std::fill_n(buffer, bufferSize, 0);
Alternatively, you can just zero initialize the array in the new expression itself
char* buffer = new char[bufferSize] {} ;
// ^ - initializer, for char this will zero out the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With