What is memset function in C and how it works

Introduction :

memset() is an important function in C. You will get this question in most C programming interviews. This function is defined in string.h file and it is used to set a block of memory programmatically.

In this post, I will show you how to use memset with example :

Definition of memset :

memset is defined as below :

void *memset(void *str, int c, size_t n)

Here,

str : It is a pointer to the starting address of the memory block that we wants to fill.

c : Value to fill. It does unsigned character conversion while we pass this value.

n: Number of bytes we want to set.

Basic example :

Let’s take a look at the example below :

#include <stdio.h>
#include <string.h>

int main()
{
    char message[20] = "Hello World !!";
    printf("Before: %s\n", message);

    memset(message, '_', 6 * sizeof(char));
    printf("After: %s\n", message);
}

It will print :

Before: Hello World !!
After: ______World !!

In this example, we have one array of characters message. We are using memset to fill the first 6 characters of this array with _.

Passing a number :

If we pass an integer value as the second parameter, it will convert that value to character using unsigned character conversion :

#include <stdio.h>
#include <string.h>

int main()
{
    char message[20] = "Hello World !!";
    printf("Before: %s\n", message);

    memset(message, 101, 6 * sizeof(char));
    printf("After: %s\n", message);
}

It will print :

Before: Hello World !!
After: eeeeeeWorld !!

Replacing within an array :

If you change the starting pointer, it starts the replacement from within the array :

#include <stdio.h>
#include <string.h>

int main()
{
    char message[20] = "Hello World !!";
    printf("Before: %s\n", message);

    memset(message+2, '*', 6 * sizeof(char));
    printf("After: %s\n", message);
}

It will print :

Before: Hello World !!
After: He******rld !!

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊❤️❤️