MEMSET Doubt ?
- Hi,
Following piece of code works perfectly :-
In the debugger, I can see that each element of array 'x' is 0 indeed. However when I do this:#include <iostream> #include <cstdio> using namespace std; int main(){ int x[10]; memset(x, 0, sizeof(x)); return 0; }
memset(x, 34, sizeof(x));
Then each value of x is some random value, sometimes 10 digits long. Actually all I want to do is, fill the array 'x' with a particular value WITHOUT running for loop from 1 to 10 and manually substituting the value like this:
x[i] = 34;
I looked on the internet and found memset but it only works for 0.
Thanks
Amare.
Answers
- It is not a random number. memset(x, 34, sizeof(x)); sets every byte in x to 34. Each int will be 0x22222222 = decimal 572662306, which should be the number the debugger showed you.
Why not use
for (int n=0; n<(sizeof(x)/sizeof(x[0])); n++) x[n] = 34?- Marked As Answer byAmare1982 Friday, November 06, 2009 7:36 PM
Memset fills a byte array, but you want to fill an array consisting of int. Each integer consists of several bytes and each byte is set to 34. As a result the whole integer does not contain the expected value.
Try fill and fill_n functions declared in <algorithm>:
fill_n(x, 10, 34);
- Marked As Answer byAmare1982 Friday, November 06, 2009 7:36 PM
All Replies
- It is not a random number. memset(x, 34, sizeof(x)); sets every byte in x to 34. Each int will be 0x22222222 = decimal 572662306, which should be the number the debugger showed you.
Why not use
for (int n=0; n<(sizeof(x)/sizeof(x[0])); n++) x[n] = 34?- Marked As Answer byAmare1982 Friday, November 06, 2009 7:36 PM
Memset fills a byte array, but you want to fill an array consisting of int. Each integer consists of several bytes and each byte is set to 34. As a result the whole integer does not contain the expected value.
Try fill and fill_n functions declared in <algorithm>:
fill_n(x, 10, 34);
- Marked As Answer byAmare1982 Friday, November 06, 2009 7:36 PM
- Thanks hgn for the help.
- Thanks Viorel_ ! Your suggested fill_n function is what I have been looking for.
Thanks for the help.


