![]() |
|
Using memset to initialize? |
Bob Keane
Member #7,342
June 2006
|
Thinking in C++ Volume I Second Edition said: The Standard C library function memset( ) (in <cstring>) is used for convenience in the program above. It sets all memory starting at a particular address (the first argument) to a particular value (the second argument) for n bytes past the starting address (n is the third argument). Of course, you could have simply used a loop to iterate through all the memory, but memset( ) is available, well-tested (so it’s less likely you’ll introduce an error), and probably more efficient than if you coded it by hand. Is using memset the same as: int array[5]; for(int i=0, i,5; i++) array[i]=0;
My confusion is how does memset know where to stop? By reading this sig, I, the reader, agree to render my soul to Bob Keane. I, the reader, understand this is a legally binding contract and freely render my soul. |
Goalie Ca
Member #2,579
July 2002
![]() |
void * memset ( void * ptr, int val, size_t num ); ptr is starting address, num is number of bytes, val is what to set it to. Use sizeof. in c++ you should be using std::fill instead. ------------- |
Timorg
Member #2,028
March 2002
|
void * memset ( void * ptr, int value, size_t num ); The 'num' parameter tells it how many bytes to set to to 'value'. The equivalent code would be int array[5]; memset(array, 0, sizeof(int) * 5);
____________________________________________________________________________________________ |
Bob Keane
Member #7,342
June 2006
|
Timorg said: memset(array, 0, sizeof(int) * 5 ) That is what I was looking for. The book left the number of elements out of the example. By reading this sig, I, the reader, agree to render my soul to Bob Keane. I, the reader, understand this is a legally binding contract and freely render my soul. |
Thomas Fjellstrom
Member #476
June 2000
![]() |
Or if its always a static array: memset(array, 0, sizeof(array)); -- |
anonymous
Member #8025
November 2006
|
Actually the book's code is alright. Read it more carefully. If you are declaring an array, you can just zero-initialize it right away: int arr[5] = {}; When the array is a class member, you can zero-initialize it in the constructor: class X { int arr[5]; public: X(): arr() {} }; In the book's example, it is used in another method, though, so some function is needed to zero out the memory. Why it chooses memset over std::fill or std::fill_n is somewhat unclear, though. |
LennyLen
Member #5,313
December 2004
![]() |
Bob Keane
Member #7,342
June 2006
|
In my defense, it says n bytes past the first argument, not elements. That can be confusing to a newb. By reading this sig, I, the reader, agree to render my soul to Bob Keane. I, the reader, understand this is a legally binding contract and freely render my soul. |
|