Home
Aptitude
Categories


Home » C solved programs » C string programs

memcpy() function in C with Example



string.h – memcpy() function with example: Here, we are going to learn about the memcpy() function – which is used to copy a block of memory from one location to another.
Submitted by IncludeHelp, on December 06, 2018

memcpy() function

memcpy() is a library function, which is declared in the “string.h” header file - it is used to copy a block of memory from one location to another (it can also be considered as to copy a string to another).

Syntax of memcpy():

    memcpy(void*str1, const void* str2, size_t n);

It copies n bytes of str2 to str1.

Example 1) Copying a string to another (all bytes of a string to another)

#include <stdio.h>
#include <string.h>
#define MAX_CHAR 50

int main(void) {
	char str1[MAX_CHAR] = "Hello World!";
	char str2[MAX_CHAR] = "Nothing is impossible";

	printf("Before copying...\n");
	printf("str1: %s\n",str1);
	printf("str2: %s\n",str2);

	//copying all bytes of str2 to str1
	memcpy(str1, str2, strlen(str2));

	printf("After copying...\n");
	printf("str1: %s\n", str1);
	printf("str2: %s\n", str2);
	
	return 0;
}

Output

Before copying...
str1: Hello World!
str2: Nothing is impossible
After copying...
str1: Nothing is impossible
str2: Nothing is impossible



Example 2) Copying some of the bytes from a byte array to another array

#include <stdio.h>
#include <string.h>
#define MAXLEN 11

//function to print array 
void printArray(unsigned char str[], int length){
	int i;
	for(i=0; i<length;i++)
		printf("%02X ", str[i]);
	printf("\n");
}

int main(void) {
	unsigned char arr1[MAXLEN] = {0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0x95};
	unsigned char arr2[MAXLEN] = {0};

	printf("Before copying...\n");
	printf("arr1: "); printArray(arr1, strlen(arr1));
	printf("arr2: "); printArray(arr2, strlen(arr2));

	//copying 5 bytes of arr1 to arr2
	memcpy(arr2, arr1, 5);
	printf("After copying...\n");
	printf("arr1: "); printArray(arr1, strlen(arr1));
	printf("arr2: "); printArray(arr2, strlen(arr2));
	
	return 0;
}

Output

Before copying...
arr1: 10 20 30 40 50 60 70 80 90 95
arr2:
After copying...
arr1: 10 20 30 40 50 60 70 80 90 95
arr2: 10 20 30 40 50 





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.