logo

memcpy() i C

Memcpy()-funksjonen kalles også Copy Memory Block-funksjonen. Den brukes til å lage en kopi av et spesifisert utvalg av tegn. Funksjonen er bare i stand til å kopiere objektene fra en minneblokk til en annen minneblokk hvis de begge ikke overlapper på noe tidspunkt.

Syntaks

Syntaksen for memcpy()-funksjonen i C-språket er som følger:

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

Memcpy()-funksjonen vil kopiere det n spesifiserte tegnet fra kildematrisen eller plasseringen. I dette tilfellet er det arr1 til destinasjonsstedet som er arr2. Både arr1 og arr2 er pekere som peker til henholdsvis kilden og destinasjonsstedet.

Parameter eller argumenter sendt i memcpy()

    arr1:det er den første parameteren i funksjonen som spesifiserer plasseringen av kildeminneblokken. Den representerer matrisen som vil bli kopiert til destinasjonen.arr2:Den andre parameteren i funksjonen spesifiserer plasseringen av destinasjonsminneblokken. Den representerer matrisen der minneblokken skal kopieres.n:Den spesifiserer antall tegn som er kopiert fra kilde til destinasjon.

Komme tilbake

Den returnerer en peker som er arr1.

Overskriftsfil

Siden memcpy()-funksjonen er definert i string.h-headerfilen, er det nødvendig å inkludere den i koden for å implementere funksjonen.

 #include 

La oss se hvordan du implementerer memcpy()-funksjonen i C-programmet.

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

Merk: Det er nødvendig å sette den siste indeksen som null i den kopierte matrisen, siden funksjonen bare kopierer dataene og ikke initialiserer selve minnet. Strengen forventer en nullverdi for å avslutte strengen.

Viktige fakta som må gjøres rede for før du implementerer memcpy() i C-programmering:

  • Memcpy()-funksjonen er deklarert i string.h-headerfilen. Så programmereren må sørge for å inkludere filen i koden.
  • Størrelsen på bufferen som innholdet skal kopieres i må være større enn antall byte som skal kopieres inn i bufferen.
  • Det fungerer ikke når objektene overlapper hverandre. Atferden er udefinert hvis vi prøver å utføre funksjonen på objektene som overlapper.
  • Det er nødvendig å legge til et nulltegn når du bruker strengene, da det ikke sjekker for de avsluttende nulltegnene i strengene.
  • Funksjonens virkemåte vil ikke bli definert hvis funksjonen vil få tilgang til bufferen utover størrelsen på den. Det er bedre å sjekke bufferstørrelsen ved å bruke sizeof()-funksjonen.
  • Det sikrer ikke at destinasjonsminneblokken er gyldig i systemets minne eller ikke.
 #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; } 

Produksjon:

binær søkepython
memcpy() i C

Oppførselen til koden er ikke definert fordi den nye pekeren ikke peker til noen gyldig plassering. Derfor vil ikke programmet fungere skikkelig. I noen kompilatorer kan det også returnere en feil. Destinasjonspekeren i tilfellet ovenfor er ugyldig.

  • Memcpy()-funksjonen utfører heller ikke valideringen av kildebufferen.
 #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; } 

Produksjon:

memcpy() i C

Utgangen, i dette tilfellet, er også lik den i tilfellet ovenfor, der destinasjonen ikke ble spesifisert. Den eneste forskjellen her er at den ikke vil returnere noen kompileringsfeil. Den vil bare vise udefinert oppførsel siden kildepekeren ikke peker til noen definert plassering.

  • Memcpy()-funksjonene fungerer på bytenivået til dataene. Derfor bør verdien av n alltid være i byte for ønskede resultater.
  • I syntaksen for memcpy()-funksjonen blir pekerne erklært ugyldige * for både kilde- og destinasjonsminneblokken, noe som betyr at de kan brukes til å peke mot alle typer data.

La oss se noen eksempler på implementering av memcpy()-funksjonen for forskjellige datatyper.

Implementering av memcpy()-funksjonen med data av char-type

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

Produksjon:

memcpy() i C

Her har vi initialisert to arrays av størrelse 30. sourcearr[] inneholder dataene som skal kopieres inn i destarr. Vi brukte memcpy()-funksjonen for å lagre dataene i destarr[].

Implementering av memcpy(0-funksjon med heltallstypedata

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

Produksjon:

memcpy() i C

I koden ovenfor har vi definert strukturen. Vi har brukt memcpy()-funksjonen to ganger. Første gang vi brukte den til å kopiere strengen til prsn1, brukte vi den andre gangen til å kopiere dataene fra prsn1 til prsn2.

Definer memcpy()-funksjonen din i programmeringsspråket C

Implementering av memcpy()-funksjonen i programmeringsspråket C er relativt enkelt. Logikken er ganske enkel bak memcpy()-funksjonen. For å implementere memcpy()-funksjonen må du skrive inn kildeadressen og destinasjonsadressen til char*(1 byte). Når typecastingen er utført, kopierer du innholdet fra kildematrisen til destinasjonsadressen. Vi må dele dataene byte for byte. Gjenta dette trinnet til du har fullført n enheter, der n er de spesifiserte bytene til dataene som skal kopieres.

La oss kode vår egen memcpy() funksjon:

Merk: Funksjonen nedenfor fungerer på samme måte som selve memcpy()-funksjonen, men mange tilfeller er fortsatt ikke tatt med i denne brukerdefinerte funksjonen. Ved å bruke memcpy()-funksjonen din kan du bestemme spesifikke forhold som skal inkluderes i funksjonen. Men hvis betingelsene ikke er spesifisert, er det foretrukket å bruke memcpy()-funksjonen definert i bibliotekfunksjonen.

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

La oss skrive en driverkode for å sjekke at koden ovenfor fungerer som den skal på ikke.

instansiering i java

Driverkode for å teste MemCpy()-funksjonen

I koden nedenfor vil vi bruke arr1 til å kopiere dataene inn i arr2 ved å bruke MemCpy() funksjonen.

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

Produksjon:

memcpy() i C