How to Make Use of Memset Function in C++

C++ provides so many tools to help you for every single bit of coding from simple tasks to more complex ones. It also provides you to play with memory. There are many useful built-in memory functions provided by C++, one of them is memset which is short form of memory set. Memset can be used to edit specific block of memory and you can change those memory blocks to any character value you desire. So it is very helpful if you want to exchange some specific characters of a string. Following step by step guide will help you to use memset function in C++.

Instructions

  • 1

    First of all you need to learn the syntax of memset function, the syntax is illustrated below:


    *memset (void *source, int value, size_t number);


    Here source will be the pointer to the memory block you wish to play with. Value represents character you want to assign and number describes the number to be set. Memset will set the values of the specified memory block starting from first number bytes.

  • 2

    Add string.h library in your code by using following line:


    #include

  • 3

    Example:


    Following example code will help you to utilize memset more efficiently. In this example we will initialize a string and then we will change certain memory blocks of that strings to a value. We will also initialize a very large array to a value, for an array we can use a for loop as well but using for loop is very very slow process as compared to memset.


    #include


    #include


    using namespace std;


    int main (){


    char str [ ] = “abcdefghi”;


    char arr[88888];


    // to change first four characters of str to Z.


    memset(str, ‘Z’, 4);


    //To initialize a large array


    memset(arr, ‘\0’, sizeof(arr));


    puts (str);


    return 0;


    }


    The output of the above program will be “ZZZZefghi”. Note that first four bytes of str has been set to Z by using memset.

Leave a Reply

Your email address will not be published. Required fields are marked *


eight − = 7