The memset( ) function can be used to initialize a dynamically allocated byte, or bytes, to a specific character. The prototype for memset( ) looks like this:
void *memset(void *dest, int cchar, size_t count);
Once the memset( ) function is called, dest points to count bytes of memory initialized to the character cchar. The following example program demonstrates a dynamic structure declaration:
// // memset.cpp // C++ program demonstrating the function memset( ), // which can initialize dynamically allocated memory. // Copyright (c) Chris H. Pappas and William H. Murray, 1998 //
pstkinitialized = new keybits; memset(pstkinitialized, 0, sizeof(keybits)); }
Because of the memset( ) function,the dynamically allocated structure pointed to by pstkinitialized contains all zeros. The call to the function memset( ) also used the sizeof( ) operator instead of hardwiring the statement to a “magic number.” The use of sizeof( )allows the algorithm to automatically adjust to the size of any object passed to it. Remember, too, that C++ does not require the struct keyword to precede a structure tag field (keybits) when defining structure variables, as is the case with pstkinitialized.