memset doesn't work as expected

A

Andrew Koenig

int *graph = new int[16];
std::fill(graph, 16, 0);
std::fill_n(graph, 16, 0);
or
std::fill(graph, graph+16, 0);

Right you are. I posted too quickly after noting the following text in the
standard:

template<class ForwardIterator, class T>
void fill(ForwardIterator first, ForwardIterator last, const T&
value);
template<class OutputIterator, class Size, class T>
void fill_n(OutputIterator first, Size n, const T& value);

and missed the _n in the second declaration. That's what I get for not
compiling my examples :)
 
R

red floyd

Andrew said:
int *graph = new int[16];
std::fill(graph, 16, 0);
std::fill_n(graph, 16, 0);
or
std::fill(graph, graph+16, 0);

Right you are. I posted too quickly after noting the following text in the
standard:

template<class ForwardIterator, class T>
void fill(ForwardIterator first, ForwardIterator last, const T&
value);
template<class OutputIterator, class Size, class T>
void fill_n(OutputIterator first, Size n, const T& value);

and missed the _n in the second declaration. That's what I get for not
compiling my examples :)

I figured it was something like that... the Holy Standard is a bit ...
densely written.

Hey, I look at it like this... Where else could a schlub like me get
away with correcting one of the recognized leaders in his field? :)
 
A

Andrey Tarasevich

thomas said:
or can I new a piece of memory and set it to zero in the mean time?

Yes, in case of scalar types (as 'int'). You could just do

int *graph = new int[16]();

and that's it.
 
A

Andrey Tarasevich

James said:
...
Theoretically, at least, memset of 0 doesn't even work for all
POD types. The only thing it's guaranteed to work for are
integral types (and I'm not even sure about those---int's can
have padding bits as well).
...

Zeroing integral objects with 'memset' became legal in C99 and only
after the first (first?) corrigendum. Formally, it is still not
guaranteed to work in C++ and C89/90.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,156
Latest member
KetoBurnSupplement
Top