C – Buffer manipulation functions

Prev     Next

  • Buffer manipulation functions in C work on the address of the memory block rather than the values inside the address.
  • Example programs for memset(), memcpy(), memmove(), memcmp(), memicmp() and memchr() functions are given below.
Functions
Description
memset() It is used to initialize a specified number of bytes to null or any other value in the buffer
memcpy() It is used to copy a specified number of bytes from one memory to another
memmove() It is used to copy a specified number of bytes from one memory to another or to overlap on same memory. 
Difference between memmove and memcpy is, overlap can happen on memmove whereas memcpy should be done in non-destructive way
memcmp() It is used to compare specified number of characters from two buffers
memicmp() It is used to compare specified number of characters from two buffers  regardless of the case of the characters
memchr() It is used to locate the first occurrence of the character in the specified string

Example program for memset() function in C:

memset( ) function is used to initialize specified number of bytes to null or to any other value in the buffer.

 Output:

Values before memset
a[0] = 0 , a[1] = 0 , a[2] = 0 , a[3] = 0 , a[4] = 0
Values after memset
a[0] = 3 , a[1] = 3 , a[2] = 3 , a[3] = 3 , a[4] = 3

Example program for memcpy() function in C:

memcpy( ) function is used to copy a specified number of bytes from one memory to another.

Output:

Elements in str1 are copied to str2 .
str1 = fresh
str2 = fresh

Example program for memmove() function in C:

memmove( ) function is used to copy a specified number of bytes from one memory to another or to overlap on same memory.

 Output:

str1 before memmove
str1 = fresh
Elements in str1 are moved/overlapped on str1 .
str1 = frfresh

Example program for memcmp() function in C:

memcmp( ) function is used to compare specified number of characters from two buffers.

 Output:

Elements in str1 and str2 are not same.

Example program for memicmp() function in C:

  • memicmp( ) function is used to compare specified number of characters from two buffers  regardless of the case of the characters.
  • If we use memcmp() function instead of memicmp, the output of the below program will be “Elements in str1 and str2 are not same”.

 Output:

Elements in str1 and str2 are same.

Example program for memchr() function in C:

memchr( ) function is used to locate the first occurrence of the character in the specified string.

Output:

character ‘h’ is found at position 5.

Prev     Next





Share this website !!!
Facebook Twitter Linkedin

Close
We Support JALLIKATTU !!!
We Support JALLIKATTU!
By Fresh2Refresh.com
Show Your Support as well. Thanks!