logo

memcpy() v C

Funkcia memcpy() sa tiež nazýva funkcia Kopírovať pamäťový blok. Používa sa na vytvorenie kópie určeného rozsahu znakov. Funkcia je schopná skopírovať objekty z jedného pamäťového bloku do druhého pamäťového bloku iba vtedy, ak sa oba v žiadnom bode neprekrývajú.

Syntax

Syntax funkcie memcpy() v jazyku C je nasledovná:

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

Funkcia memcpy() skopíruje zadaný znak n zo zdrojového poľa alebo umiestnenia. V tomto prípade je to arr1 do cieľového miesta, ktoré je arr2. Oba arr1 a arr2 sú ukazovatele, ktoré ukazujú na zdrojové a cieľové umiestnenie.

Parameter alebo argumenty odovzdané v memcpy()

    arr1:je to prvý parameter vo funkcii, ktorý určuje umiestnenie zdrojového pamäťového bloku. Predstavuje pole, ktoré sa skopíruje do cieľa.arr2:Druhý parameter vo funkcii určuje umiestnenie cieľového pamäťového bloku. Predstavuje pole, do ktorého sa skopíruje pamäťový blok.n:Určuje počet znakov skopírovaných zo zdroja do cieľa.

Návrat

Vracia ukazovateľ, ktorým je arr1.

podreťazec reťazca java

Hlavičkový súbor

Keďže funkcia memcpy() je definovaná v hlavičkovom súbore string.h, na implementáciu funkcie je potrebné ju zahrnúť do kódu.

 #include 

Pozrime sa, ako implementovať funkciu memcpy() v programe 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; } 

Poznámka: V skopírovanom poli je potrebné nastaviť posledný index ako null, pretože funkcia iba kopíruje dáta a neinicializuje samotnú pamäť. Reťazec očakáva nulovú hodnotu na ukončenie reťazca.

Dôležité fakty, ktoré je potrebné zohľadniť pred implementáciou memcpy() v programovaní C:

  • Funkcia memcpy() je deklarovaná v hlavičkovom súbore string.h. Takže programátor musí zabezpečiť, aby súbor zahrnul do kódu.
  • Veľkosť vyrovnávacej pamäte, do ktorej sa má obsah skopírovať, musí byť väčšia ako počet bajtov, ktoré sa majú skopírovať do vyrovnávacej pamäte.
  • Nefunguje, keď sa objekty prekrývajú. Správanie je nedefinované, ak sa pokúsime vykonať funkciu na objektoch, ktoré sa prekrývajú.
  • Pri použití reťazcov je potrebné pridať nulový znak, pretože nekontroluje koncové nulové znaky v reťazcoch.
  • Správanie funkcie nebude definované, ak funkcia bude pristupovať do vyrovnávacej pamäte nad jej veľkosť. Je lepšie skontrolovať veľkosť vyrovnávacej pamäte pomocou funkcie sizeof().
  • Nezaručuje, že cieľový pamäťový blok je platný v pamäti systému alebo nie.
 #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; } 

Výkon:

memcpy() v C

Správanie kódu nie je definované, pretože nový ukazovateľ neukazuje na žiadne platné miesto. Program preto nebude správne fungovať. V niektorých kompilátoroch môže tiež vrátiť chybu. Ukazovateľ cieľa vo vyššie uvedenom prípade je neplatný.

  • Funkcia memcpy() tiež nevykonáva validáciu zdrojovej vyrovnávacej pamäte.
 #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; } 

Výkon:

memcpy() v C

Výstup je v tomto prípade tiež podobný ako vo vyššie uvedenom prípade, kde nebolo určené miesto určenia. Jediný rozdiel je v tom, že by to nevrátilo žiadnu chybu kompilácie. Ukáže len nedefinované správanie, pretože zdrojový ukazovateľ neukazuje na žiadne definované miesto.

zoznam triediť podľa java
  • Funkcie memcpy() pracujú na úrovni bajtov údajov. Preto by hodnota n mala byť vždy v bajtoch, aby sa dosiahli požadované výsledky.
  • V syntaxi funkcie memcpy() sú ukazovatele deklarované ako neplatné * pre zdrojový aj cieľový blok pamäte, čo znamená, že ich možno použiť na ukazovanie na akýkoľvek typ údajov.

Pozrime sa na niekoľko príkladov implementácie funkcie memcpy() pre rôzne typy údajov.

Implementácia funkcie memcpy() s údajmi typu 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; } 

Výkon:

pomocný policajný komisár
memcpy() v C

Tu sme inicializovali dve polia veľkosti 30. Sourcearr[] obsahuje údaje, ktoré sa majú skopírovať do destarr. Na uloženie údajov do destarr[] sme použili funkciu memcpy().

Implementácia funkcie memcpy(0 s údajmi typu celé číslo

 #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++){>

Výkon:

memcpy() v C

Vo vyššie uvedenom kóde sme definovali štruktúru. Funkciu memcpy() sme použili dvakrát. Prvýkrát sme ho použili na skopírovanie reťazca do prsn1, druhýkrát sme ho použili na skopírovanie údajov z prsn1 do prsn2.

Definujte svoju funkciu memcpy() v programovacom jazyku C

Implementácia funkcie memcpy() v programovacom jazyku C je pomerne jednoduchá. Logika funkcie memcpy() je celkom jednoduchá. Ak chcete implementovať funkciu memcpy(), musíte zdrojovú adresu a cieľovú adresu pretypovať na char*(1 bajt). Po vykonaní pretypovania teraz skopírujte obsah zo zdrojového poľa na cieľovú adresu. Údaje musíme zdieľať bajt po bajte. Tento krok opakujte, kým nedokončíte n jednotiek, kde n sú špecifikované bajty údajov, ktoré sa majú skopírovať.

Poďme nakódovať našu vlastnú funkciu memcpy():

Poznámka: Funkcia uvedená nižšie funguje podobne ako skutočná funkcia memcpy(), ale veľa prípadov stále nie je zohľadnených v tejto funkcii definovanej používateľom. Pomocou funkcie memcpy() môžete rozhodnúť o konkrétnych podmienkach, ktoré budú zahrnuté do funkcie. Ak však podmienky nie sú špecifikované, je výhodné použiť funkciu memcpy() definovanú vo funkcii knižnice.

 //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; } 

Napíšme kód ovládača, aby sme skontrolovali, či vyššie uvedený kód funguje správne.

výroková logika

Kód ovládača na testovanie funkcie MemCpy().

V nižšie uvedenom kóde použijeme arr1 na skopírovanie údajov do arr2 pomocou funkcie 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; } 

Výkon:

memcpy() v C