Q:

Write a C program to Set buffer with specific value using memset in C - Example of memset()

0

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).

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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 .

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C programming Basic Input, Output, if else, Ternary Operator based Programs

Similar questions


need a help?


find thousands of online teachers now
Write a C program to evaluate the net salary of an... >>
<< Write a C program to Calculate Employee and Emplo...