memcpy in C
×


memcpy in C

198

"memcpy" in C is a standard library function defined in <string.h>.

 It efficiently copies a specified number of bytes from one memory location to another.

Syntax of "memcpy" in C:

#include<string.h> 
void *memcpy(void *dest, const void *src, size_t n);

Parameters:

dest represents the pointer to the target array where the data will be replicated.

src: Pointer to the source of data to be copied.

n: Number of bytes to copy.


Implementation Definition:

The "memcpy" function copies "n" bytes from the memory area pointed to by "src" to the memory area pointed to by "dest".

It does not check for buffer overrun, so the destination buffer must be large enough to hold the copied data.


Important Facts:

It is a common practice to use "memcpy" for copying large chunks of memory efficiently.

It is faster than copying byte by byte using loops.

The function can be used for both overlapping and non-overlapping memory regions.


Examples:

Copying Array Elements:

// program for copying array elements
#include<stdio.h> 
#include<string.h>

int main() {
    char src[] = "Hello, memcpy!";
    char dest[20];
    
    memcpy(dest, src, strlen(src) + 1);
    
    printf("Copied string: %s\n", dest);
    return 0;
}
	

Output:

Copied string: Hello, memcpy!

Copying Structures:

// program for copying structures
#include<stdio.h> 
#include<string.h>

struct Person {
    char name[20];
    int age;
};

int main() {
    struct Person person1 = {"John", 30};
    struct Person person2;
    
    memcpy(&person2, &person1, sizeof(struct Person));
    
    printf("Copied person: %s, %d years old\n", person2.name, person2.age);
    return 0;
}	

Output:

Copied person: John, 30 years old

Copying Integer Array:

// program for "memcpy" function in C
#include<stdio.h> 
#include<string.h> 

int main() {
    int src[] = {1, 2, 3, 4, 5};
    int dest[5];
    
    memcpy(dest, src, sizeof(src));
    
    printf("Copied array: ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", dest[i]);
    }
    printf("\n");
    return 0;
}	

Output:

Copied array: 1 2 3 4 5 


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments