How to Use the Memset Function in C++

The C++ memset function is short for "memory set." It sets a specified block of memory to a specified character, overwriting the original data. It does not check for overflow and does not use an intermediate buffer. The following steps will help you use memset.

Instructions

    • 1

      Learn the syntax of memset in C++. The complete syntax is void *memset (void *source, int value, size_t num);.

    • 2

      Know that source is a pointer to the block of memory to fill and value is the character to be set. This byte value is internally converted to an unsigned char. Num is the number of be set. Memset will set the first num bytes of the memory pointed to by source to the specified value and return source.

    • 3

      Understand that the C++ memset function is kept in the cstring library. You may need to include the string.h header file to use this function.

    • 4

      Look at the following complete program for some simple examples of how to use memset. Note the use of memset to initialize an array instead of using a loop:

      #include
      #include

      int main ()
      {
      int i=0;
      char string1[] = "1234567890";
      char an_array[99999];
      /* change the first three bytes of string1 to "X" */
      memset (string1,'X',3);
      /* preferred method to initialize an array */
      memset (an_array, '\0', sizeof(an_array));
      /* slower than memset as the array gets large */
      while (i {
      an_array[i]='\0';
      i++;
      }
      puts (string1);
      return 0;
      }

    • 5

      Observe the following output for this program:

      XXX4567890

Related Searches:

Resources

Comments

You May Also Like

Related Ads

Featured