C++ Programming/Code/Standard C Library/Functions/memset

memset

Syntax
#include <cstring>
void* memset( void* buffer, int ch, size_t count );

The function memset() copies ch into the first count characters of buffer, and returns buffer. memset() is useful for intializing a section of memory to some value. For example, this command:

const int ARRAY_LENGTH;
char the_array[ARRAY_LENGTH];
...
// zero out the contents of the_array
memset( the_array, '\0', ARRAY_LENGTH );

...is a very efficient way to set all values of the_array to zero.

The table below compares two different methods for initializing an array of characters: a for loop versus memset(). As the size of the data being initialized increases, memset() clearly gets the job done much more quickly:

Input sizeInitialized with a for loopInitialized with memset()
10000.0160.017
100000.0550.013
1000000.4430.029
10000004.3370.291
Related topics
memcmp - memcpy - memmove
Category:Book:C++ Programming#Code/Standard%20C%20Library/Functions/memset%20
Category:Book:C++ Programming