Set buffer with specific value using memset in C - Example of memset()

In this C program, we will learn how to set a particular value to the buffer (character array)? To set the value to the buffer, we will use memset() function.

This C program will demonstrate use of memset(), in this code snippet we will learn how to set specific value using memset() to the buffer.

memset() is a library function of string.h header file which assigns given value to the given number of bytes (characters).

Set buffer (character array) with specific value in C

/*Set buffer with specific value using memset in C - 
Example of memset()*/
 
#include <stdio.h>
#include <string.h>
 
 
int main()
{
    unsigned char buffer[10]={0};
    int i;
     
    printf("buffer: %s\n",buffer);
     
    //set value with space
    memset(buffer,' ', 9);  //last byte should be null
    printf("buffer (memset with space): %s",buffer); printf(".\n");
 
    //set value with 'x'
    memset(buffer,'x', 9);  //last byte should be null
    printf("buffer (memset with x): %s",buffer); printf(".\n"); 
 
    //set value with value 15
    memset(buffer,15, 9);   //last byte should be null
    printf("buffer (memset with value 15): %s",buffer); printf(".\n");      
    printf("buffer (memset with value 15 printing integer values:\n*** LAST VALUE WILL BE NULL ***):\n");
    for(i=0;i<10;i++){
        printf("%02d ",buffer[i]);
    }
    printf(".\n");
     
    return 0;
}

Output

buffer: 
buffer (memset with space):          .
buffer (memset with x): xxxxxxxxx.
buffer (memset with value 15): .
buffer (memset with value 15 printing integer values:
*** LAST VALUE WILL BE NULL ***):
15 15 15 15 15 15 15 15 15 00 .

C Basic Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.