memccpy in C

In this blog post, you will learn about the memccpy in C with the help of programming examples.

The memccpy function copies characters from the object pointed to by src into the object pointed to by dest. The copies of characters are stopped after any of the next two conditions are satisfied:

1. The first occurrence of character c (converted to an unsigned char) is copied.

2. n characters are copied.

 

Syntax memccpy in C:

void *memccpy(void * restrict dest, const void * restrict src, int c, size_t count);

 

memccpy Parameters:

The memccpy() function accepts the following parameters:

dst — pointer to the destination object

src — pointer to the source object

c —terminating character (converted to an unsigned char).

n — Number of bytes to copy.

 

memccpy return value:

The memccpy function returns a pointer to the character after the copy of c in dest or a null pointer if c was not found in the first n characters of src.

 

Example program to describe how to use memccpy in C:

The following program illustrates the working of the memccpy function in the C language.

#include <stdio.h>
#include <string.h>


int main()
{
    char src[30] = "Hi Aticleworld.com";
    char dest[31] = {0};

    printf("memccpy 30 characters or to character '.'\n");
    printf("Source: %s\n", src);
    char *pDest = memccpy(dest, src, '.', 30);
    *pDest = '\0'; //append null
    printf( "Result: %s\n", dest);
    printf( "Length: %ld characters\n", strlen(dest) );

    return 0;
}

Output:

memccpy in c

 

Explanation:

In the above code in place of n (number of bytes that you want to copy), we have used the 30. And the terminating character is'.'(dot). The memccpy function copies characters from the src buffer to the dest buffer and stops after the first copies of '.'

 

Undefined Behavior of memccpy() :

The behavior of memccpy() is undefined if:

1. Copying takes place between objects that overlap.

2.Either dest or src is a null pointer.

3.Either dest or src is an invalid pointer.

4.Access occurs beyond the end of the dest array.

5.Access occurs beyond the end of the src array.

 

Program when terminating char not found in the first n characters of memccpy in C:

The following program illustrates that the memcpy() function returns a null pointer when the “terminating character” is not found in the first n characters.

#include <stdio.h>
#include <string.h>


int main()
{
    char src[50] = "Aticleworld is place to learn new concept";
    char dest[51] = {0};

    printf("Source: %s\n", src);
    char *pDest = memccpy(dest, src, '#', 50);
    if(pDest == NULL)
    {
        printf("NULL POINTER: Getting null pointer\n");
    }

    printf( "Result: %s\n", dest);

    return 0;
}

Output:

Source: Aticleworld is place to learn new concept
NULL POINTER: Getting null pointer
Result: Aticleworld is place to learn new concept

 

 

Recommended Post:

Leave a Reply

Your email address will not be published. Required fields are marked *