logo

memcpy() у C

Функція memcpy() також називається функцією Copy Memory Block. Він використовується для створення копії заданого діапазону символів. Функція здатна копіювати об’єкти з одного блоку пам’яті в інший блок пам’яті, лише якщо вони обидва не перекриваються в будь-якій точці.

Синтаксис

Синтаксис функції memcpy() мовою C такий:

 void *memcpy(void *arr1, const void *arr2, size_t n); 

Функція memcpy() скопіює вказаний символ n із вихідного масиву або розташування. У цьому випадку це arr1 до місця призначення, яке є arr2. Обидва arr1 і arr2 є покажчиками, які вказують на розташування джерела та призначення відповідно.

Параметр або аргументи, передані в memcpy()

    прибуття1:це перший параметр у функції, який визначає розташування вихідного блоку пам'яті. Він представляє масив, який буде скопійовано до місця призначення.приб.2:Другий параметр у функції вказує розташування цільового блоку пам'яті. Він представляє масив, куди буде скопійовано блок пам'яті.n:Він визначає кількість символів, скопійованих із джерела до місця призначення.

Повернення

Він повертає покажчик, який є arr1.

Заголовний файл

Оскільки функція memcpy() визначена у файлі заголовка string.h, її необхідно включити в код для реалізації функції.

 #include 

Давайте подивимося, як реалізувати функцію memcpy() у програмі C.

 //Implementation of memcpy() in C Programming #include #include int main(int argc, const char * argv[]) { //initializing a variable that will hold the result./* Create a place to store our results */ int res; //declare the arrays for which you want to copy the data and //in which you want to copy it char orgnl[50]; char copy[50]; //Entering a string the orgnl array strcpy(orgnl, 'This is the program for implementing the memcpy() in C Program'); //use the memcpy() function to copy the characters from the source to destination. res = memcpy(copy, orgnl, 27); // we have specified n as 27 this means it will copy the first 27 character of //orgnl array to copy array //set the value for last index in the copy as 0 copy[27] = 0; //display the copied content printf('%s
', copy); return 0; } 

Примітка: необхідно встановити останній індекс як null у скопійованому масиві, оскільки функція лише копіює дані, а не ініціалізує саму пам’ять. Рядок очікує нульове значення для завершення рядка.

Важливі факти, які слід враховувати перед впровадженням memcpy() у програмування на C:

  • Функція memcpy() оголошена у файлі заголовка string.h. Тому програміст повинен переконатися, що файл включено в код.
  • Розмір буфера, у який потрібно скопіювати вміст, має бути більшим за кількість байтів, які потрібно скопіювати в буфер.
  • Це не працює, коли об'єкти перекриваються. Поведінка не визначена, якщо ми намагаємося виконати функцію на об’єктах, які перекриваються.
  • Під час використання рядків необхідно додати нульовий символ, оскільки він не перевіряє кінцеві нульові символи в рядках.
  • Поведінка функції не буде визначена, якщо функція матиме доступ до буфера, що перевищує його розмір. Перевіряти розмір буфера краще за допомогою функції sizeof().
  • Це не гарантує, що цільовий блок пам’яті дійсний у пам’яті системи чи ні.
 #include #include int main () { //The first step is to initialize the source and destination array. char* new; char orgnl[30] = 'Movetheobject'; //Print the contents before performing memcpy() function. printf('Before implementing memcpy() destination and source memory block respt is
 new = %s
 orgnl = %s
', new, orgnl); memcpy(new, orgnl, sizeof(orgnl)); //Display the content in both new and orgnl array after implementing memcpy. printf('After memcpy >> new = %s
 orgnl = %s
', new, orgnl); return 0; } 

Вихід:

javascript onload
memcpy() у C

Поведінка коду не визначена, оскільки новий покажчик не вказує на жодне дійсне розташування. Отже, програма не працюватиме належним чином. У деяких компіляторах він також може повертати помилку. Покажчик призначення у наведеному вище випадку недійсний.

  • Функція memcpy() також не виконує перевірку вихідного буфера.
 #include #include int main () { //The first step is to initialize the source and destination array. char new[10]= {1}; char *orgnl; //Print the contents before performing memcpy() function. printf('Before implementing memcpy() destination and source memory block respt is
 new = %s
 orgnl = %s
', new, orgnl); memcpy(new, orgnl, sizeof(orgnl)); //Display the content in both new and orgnl array after implementing memcpy. printf('After memcpy >> new = %s
 orgnl = %s
', new, orgnl); return 0; } 

Вихід:

memcpy() у C

Вихідні дані в цьому випадку також подібні до тих, що були в наведеному вище випадку, де призначення не було вказано. Єдина відмінність тут полягає в тому, що він не повертатиме жодної помилки компіляції. Він просто показуватиме невизначену поведінку, оскільки покажчик джерела не вказує на жодне визначене місце.

  • Функції memcpy() працюють на байтовому рівні даних. Тому для бажаних результатів значення n завжди має бути в байтах.
  • У синтаксисі функції memcpy() покажчики оголошено недійсними * як для вихідного, так і для цільового блоку пам’яті, що означає, що їх можна використовувати для вказівки на будь-який тип даних.

Давайте подивимося кілька прикладів реалізації функції memcpy() для різних типів даних.

Реалізація функції memcpy() з даними типу char

 #include #include int main() { //initialize the source array, //the data will be copied from source to destination/ char sourcearr[30] = 'This content is to be copied.'; //this is the destination array //data will be copied at this location. char destarr[30] = {0}; //copy the data stored in the sourcearr buffer into destarr buffer memcpy(destarr,sourcearr,sizeof(sourcearr)); //print the data copied into destarr printf('destination array content is now changed to
 = %s
', destarr); return 0; } 

Вихід:

memcpy() у C

Тут ми ініціалізували два масиви розміром 30. Sourcearr[] містить дані для копіювання в destarr. Ми використали функцію memcpy() для збереження даних у destarr[].

Реалізація функції memcpy(0) з даними цілого типу

 #include #include int main() { //initialize the source array, //the data will be copied from source to destination/ int sourcearr[100] = {1,2,3,4,5}; //this is the destination array //data will be copied at this location. int destarr[100] = {0}; //copy the data stored in the sourcearr buffer into destarr buffer memcpy(destarr,sourcearr,sizeof(sourcearr)); //print the data copied into destarr printf('destination array content is now changed to
&apos;); for(int i=0;i<5;i++){ printf('%d', destarr[i]); }return 0;} < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/c-tutorial/16/memcpy-c-4.webp" alt="memcpy() in C"> <p>In this code, we have stored the integers in the array. Both the arrays can store int datatype. We have used the indexes to print the elements of the destarr after copying the elements of the sourcearr into destarr.</p> <h3>Implementing the memcpy() function with struct datatype</h3> <pre> #include #include struct { char name[40]; int age; } prsn1, prsn2; int main() { // char firstname[]=&apos;Ashwin&apos;; //Using the memcpy() function to copy the data from //firstname to the struct //add it is as prsn1 name memcpy ( prsn1.name, firstname, strlen(firstname)+1 ); //initialize the age of the prsn1 prsn1.age=20; //using the memcpy() function to copy one person to another //the data will be copied from prsn1 to prsn2 memcpy ( &amp;prsn2, &amp;prsn1, sizeof(prsn1) ); //print the stored data //display the value stored after copying the data //from prsn1 to prsn2 printf (&apos;person2: %s, %d 
&apos;, prsn2.name, prsn2.age ); return 0; } </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/c-tutorial/16/memcpy-c-5.webp" alt="memcpy() in C"> <p>In the above code, we have defined the structure. We have used the memcpy() function twice. The first time we used it to copy the string into prsn1, we used it the second time to copy the data from the prsn1 to prsn2.</p> <h2>Define your memcpy() function in C Programming Language</h2> <p>Implementing the memcpy() function in the C Programming language is comparatively easy. The logic is quite simple behind the memcpy() function. To implement the memcpy() function, you must typecast the source address and the destination address to char*(1 byte). Once the typecasting is performed, now copy the contents from the source array to the destination address. We have to share the data byte by byte. Repeat this step until you have completed n units, where n is the specified bytes of the data to be copied.</p> <p>Let us code our own memcpy() function:</p> <h4>Note: The function below works similarly to the actual memcpy() function, but many cases are still not accounted for in this user-defined function. Using your memcpy() function, you can decide specific conditions to be included in the function. But if the conditions are not specified, it is preferred to use the memcpy() function defined in the library function.</h4> <pre> //this is just the function definition for the user defined memcpy() function. void * MemCpy(void* destinatn, const void* source, unsigned int cn) { char *pntDest = (char *)destinatn; const char *pntSource =( const char*)source; if((pntDest!= NULL) &amp;&amp; (pntSource!= NULL)) { while(cn) //till cn the loop will be executed { //copy the contents from source to dest //the data should be copied byte by byte *(pntDest++)= *(pntSource++); //decrement the value of cn --cn; } } return destinatn; } </pre> <p>Let us write a driver code to check that above code is working properly on not.</p> <p>Driver Code to test MemCpy() Function</p> <p>In the code below we will use the arr1 to copy the data into the arr2 by using MemCpy() function.</p> <pre> void * MemCpy(void* destinatn, const void* source, unsigned int cn) { char *pntDest = (char *)destinatn; const char *pntSource =( const char*)source; if((pntDest!= NULL) &amp;&amp; (pntSource!= NULL)) { while(cn) //till cn the loop will be executed { //copy the contents from source to dest //the data should be copied byte by byte *(pntDest++)= *(pntSource++); //decrement the value of cn --cn; } } return destinatn; } int main() { char src[20] = &apos;How Are you ?&apos;; //Source String char dst[20] = {0}; //dst buffer //copy source buffer int dst MemCpy(dst,src,sizeof(src)); printf(&apos;dst = %s
&apos;, dst); return 0; } </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/c-tutorial/16/memcpy-c-6.webp" alt="memcpy() in C"> <hr></5;i++){>

Вихід:

memcpy() у C

У наведеному вище коді ми визначили структуру. Ми використовували функцію memcpy() двічі. Перший раз ми використали його для копіювання рядка в prsn1, ми використали його вдруге, щоб скопіювати дані з prsn1 у prsn2.

Визначте свою функцію memcpy() мовою програмування C

Реалізація функції memcpy() мовою програмування C порівняно проста. Логіка функції memcpy() досить проста. Щоб реалізувати функцію memcpy(), ви повинні привести адресу джерела та адресу призначення до char*(1 байт). Після виконання приведення типів скопіюйте вміст із вихідного масиву на адресу призначення. Ми повинні ділитися даними байт за байтом. Повторюйте цей крок, доки не виконаєте n одиниць, де n — вказані байти даних, які потрібно скопіювати.

Давайте закодуємо нашу власну функцію memcpy():

Примітка. Наведена нижче функція працює подібно до фактичної функції memcpy(), але багато випадків все ще не враховано в цій призначеній для користувача функції. Використовуючи функцію memcpy(), ви можете визначити конкретні умови, які слід включити у функцію. Але якщо умови не вказані, бажано використовувати функцію memcpy(), визначену у функції бібліотеки.

 //this is just the function definition for the user defined memcpy() function. void * MemCpy(void* destinatn, const void* source, unsigned int cn) { char *pntDest = (char *)destinatn; const char *pntSource =( const char*)source; if((pntDest!= NULL) &amp;&amp; (pntSource!= NULL)) { while(cn) //till cn the loop will be executed { //copy the contents from source to dest //the data should be copied byte by byte *(pntDest++)= *(pntSource++); //decrement the value of cn --cn; } } return destinatn; } 

Давайте напишемо код драйвера, щоб перевірити, чи код вище працює належним чином на not.

mvc у рамках Spring

Код драйвера для перевірки функції MemCpy().

У коді нижче ми будемо використовувати arr1 для копіювання даних в arr2 за допомогою функції MemCpy().

 void * MemCpy(void* destinatn, const void* source, unsigned int cn) { char *pntDest = (char *)destinatn; const char *pntSource =( const char*)source; if((pntDest!= NULL) &amp;&amp; (pntSource!= NULL)) { while(cn) //till cn the loop will be executed { //copy the contents from source to dest //the data should be copied byte by byte *(pntDest++)= *(pntSource++); //decrement the value of cn --cn; } } return destinatn; } int main() { char src[20] = &apos;How Are you ?&apos;; //Source String char dst[20] = {0}; //dst buffer //copy source buffer int dst MemCpy(dst,src,sizeof(src)); printf(&apos;dst = %s
&apos;, dst); return 0; } 

Вихід:

memcpy() у C