Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set all the bits in a char array to zeros?

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.

like image 459
Lilith X Avatar asked Nov 30 '25 16:11

Lilith X


1 Answers

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.
like image 94
StoryTeller - Unslander Monica Avatar answered Dec 02 '25 07:12

StoryTeller - Unslander Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!