ADVERTISEMENT
ADVERTISEMENT

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 »



ADVERTISEMENT




ADVERTISEMENT



Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.