C memset() function
C memset() function - set bytes in memory
Syntax:
void *memset(void *dest, int c, size_t n)
The memset() function is used to set the first n bytes of dest to the value c. The value of c is converted to an unsigned character.
Parameters:
Name | Description | Required /Optional |
---|---|---|
dest | Pointer to destination. | Required |
c | Character to set. | Required |
n | Number of bytes to be set to the value. | Optional |
Return value from memset()
The value of dest.
Example: memset() function
Following program uses memset to set the first five characters of buffer to "#".
#include <stdio.h>
#include <string.h>
int main( void )
{
char buffer[] = "C programming memset function";
printf( "Before: %s\n", buffer );
memset( buffer, '#', 5 );
printf( "After: %s\n", buffer );
}
Output:
Before: C programming memset function After: #####gramming memset function
Example that uses memset() function:
Following program sets 10 bytes of the buffer to1 and the next 10 bytes to 2.
#include <string.h>
#include <stdio.h>
#define BUF_SIZE 20
int main(void)
{
char buffer[BUF_SIZE + 1];
char *string;
memset(buffer, 0, sizeof(buffer));
string = (char *) memset(buffer,'1', 10);
printf("\nBuffer contents: %s\n", string);
memset(buffer+10, '2', 10);
printf("\nBuffer contents: %s\n", buffer);
}
Output:
Buffer contents: 1111111111 Buffer contents: 11111111112222222222
C Programming Code Editor:
Previous C Programming: C memmove()
Next C Programming: C strcat()
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics