logo

memcpy() w C

Funkcja memcpy() nazywana jest także funkcją kopiowania bloku pamięci. Służy do wykonania kopii określonego zakresu znaków. Funkcja może kopiować obiekty z jednego bloku pamięci do innego bloku pamięci tylko wtedy, gdy w żadnym momencie nie nakładają się na siebie.

Składnia

Składnia funkcji memcpy() w języku C jest następująca:

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

Funkcja memcpy() skopiuje n określony znak ze źródłowej tablicy lub lokalizacji. W tym przypadku jest to arr1 do lokalizacji docelowej, czyli arr2. Zarówno arr1, jak i arr2 są wskaźnikami wskazującymi odpowiednio lokalizację źródłową i docelową.

Parametr lub argumenty przekazane w memcpy()

    tablica1:jest to pierwszy parametr funkcji określający położenie bloku pamięci źródłowej. Reprezentuje tablicę, która zostanie skopiowana do miejsca docelowego.tablica2:Drugi parametr funkcji określa lokalizację docelowego bloku pamięci. Reprezentuje tablicę, do której zostanie skopiowany blok pamięci.N:Określa liczbę znaków skopiowanych ze źródła do miejsca docelowego.

Powrót

Zwraca wskaźnik, którym jest arr1.

przycinanie JavaScriptu

Plik nagłówkowy

Ponieważ funkcja memcpy() jest zdefiniowana w pliku nagłówkowym string.h, konieczne jest uwzględnienie jej w kodzie, aby zaimplementować tę funkcję.

 #include 

Zobaczmy, jak zaimplementować funkcję memcpy() w programie 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; } 

Uwaga: Konieczne jest ustawienie ostatniego indeksu kopiowanej tablicy na null, ponieważ funkcja tylko kopiuje dane i nie inicjuje samej pamięci. Ciąg oczekuje wartości null, która zakończy ciąg.

Ważne fakty, które należy wziąć pod uwagę przed wdrożeniem memcpy() w programowaniu C:

  • Funkcja memcpy() jest zadeklarowana w pliku nagłówkowym string.h. Dlatego programista musi upewnić się, że plik zostanie dołączony do kodu.
  • Rozmiar bufora, do którego ma zostać skopiowana zawartość, musi być większy niż liczba bajtów, które mają zostać skopiowane do bufora.
  • Nie działa, gdy obiekty nakładają się na siebie. Zachowanie jest niezdefiniowane, jeśli spróbujemy wykonać funkcję na obiektach, które się nakładają.
  • Podczas używania ciągów znaków konieczne jest dodanie znaku null, ponieważ nie sprawdza on końcowych znaków null w ciągach.
  • Zachowanie funkcji nie zostanie zdefiniowane, jeśli funkcja będzie miała dostęp do bufora przekraczającego jego rozmiar. Lepiej sprawdzić rozmiar bufora za pomocą funkcji sizeof().
  • Nie gwarantuje to, że docelowy blok pamięci będzie ważny w pamięci systemu, czy też 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; } 

Wyjście:

memcpy() w C

Zachowanie kodu nie jest zdefiniowane, ponieważ nowy wskaźnik nie wskazuje żadnej prawidłowej lokalizacji. Dlatego program nie będzie działał poprawnie. W niektórych kompilatorach może również zwrócić błąd. Wskaźnik miejsca docelowego w powyższym przypadku jest nieprawidłowy.

  • Funkcja memcpy() również nie sprawdza poprawności bufora źródłowego.
 #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; } 

Wyjście:

memcpy() w C

Wynik w tym przypadku jest również podobny do tego w powyższym przypadku, gdzie nie określono miejsca docelowego. Jedyna różnica polega na tym, że nie zwraca żadnego błędu kompilacji. Będzie po prostu pokazywać niezdefiniowane zachowanie, ponieważ wskaźnik źródła nie wskazuje żadnej zdefiniowanej lokalizacji.

mapa vs zestaw
  • Funkcje memcpy() działają na poziomie bajtów danych. Dlatego, aby uzyskać pożądane wyniki, wartość n powinna zawsze być wyrażona w bajtach.
  • W składni funkcji memcpy() wskaźniki są deklarowane jako void * zarówno dla źródłowego, jak i docelowego bloku pamięci, co oznacza, że ​​można ich używać do wskazywania dowolnego typu danych.

Zobaczmy kilka przykładów implementacji funkcji memcpy() dla różnych typów danych.

Implementacja funkcji memcpy() z danymi 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; } 

Wyjście:

sieć komputerowa
memcpy() w C

Tutaj zainicjowaliśmy dwie tablice o rozmiarze 30. Sourcearr[] zawiera dane, które mają zostać skopiowane do destarr. Użyliśmy funkcji memcpy() do przechowywania danych w destarr[].

Implementacja funkcji memcpy(0 z danymi typu całkowitego

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

Wyjście:

memcpy() w C

W powyższym kodzie zdefiniowaliśmy strukturę. Dwukrotnie użyliśmy funkcji memcpy(). Za pierwszym razem użyliśmy go do skopiowania łańcucha do prsn1, użyliśmy go za drugim razem do skopiowania danych z prsn1 do prsn2.

Zdefiniuj funkcję memcpy() w języku programowania C

Implementacja funkcji memcpy() w języku programowania C jest stosunkowo łatwa. Logika funkcji memcpy() jest dość prosta. Aby zaimplementować funkcję memcpy(), musisz wpisać adres źródłowy i docelowy do postaci char*(1 bajt). Po wykonaniu rzutowania skopiuj teraz zawartość z tablicy źródłowej na adres docelowy. Musimy udostępniać dane bajt po bajcie. Powtarzaj ten krok, aż ukończysz n jednostek, gdzie n to określone bajty danych do skopiowania.

Zakodujmy własną funkcję memcpy():

Uwaga: Poniższa funkcja działa podobnie do rzeczywistej funkcji memcpy(), ale wiele przypadków nadal nie jest uwzględnianych w tej funkcji zdefiniowanej przez użytkownika. Używając funkcji memcpy(), możesz określić konkretne warunki, które mają zostać uwzględnione w tej funkcji. Jeśli jednak warunki nie są określone, preferowane jest użycie funkcji memcpy() zdefiniowanej w funkcji bibliotecznej.

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

Napiszmy kod sterownika, aby sprawdzić, czy powyższy kod działa poprawnie na nie.

czy android może grać w gamepigeon

Kod sterownika do testowania funkcji MemCpy().

W poniższym kodzie użyjemy arr1 do skopiowania danych do arr2 za pomocą funkcji 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; } 

Wyjście:

memcpy() w C