How to implement the memcpy() function in C

3 Answers

0 votes
#include <stdio.h>
#include <string.h>

void memcpy_implementation(void* dest, void* src, size_t len) {
    char* psrc = (char*)src;
    char* pdest = (char*)dest;

    for (int i = 0; i < len; i++)
        pdest[i] = psrc[i];
}

int main()
{
    char src[] = "c programming";
    char dest[64];

    memcpy_implementation(dest, src, strlen(src) + 1);
    
    printf("%s", dest);

    return 0;
}




/*
run:

c programming

*/

 



answered Jul 6, 2018 by avibootz
edited Nov 11, 2022 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>

void memcpy_implementation(void* dest, void* src, size_t len) {
    char* psrc = (char*)src;
    char* pdest = (char*)dest;

    for (int i = 0; i < len; i++)
        pdest[i] = psrc[i];
}

int main()
{
    int int_src[] = { 13, 65, 99, 150 };
    int size = sizeof(int_src) / sizeof(int_src[0]);

    int* int_dest = (int*)calloc(size, sizeof(int));

    memcpy_implementation(int_dest, int_src, sizeof(int_src));

    for (int i = 0; i < size; i++)
        printf("%4d", int_dest[i]);

    free(int_dest);

    return 0;
}




/*
run:

  13  65  99 150

*/

 



answered Jul 6, 2018 by avibootz
edited Nov 11, 2022 by avibootz
0 votes
#include <stdio.h>
 
void* memcpy_implementation(void* s1, const void* s2, size_t n) {
    // copy n characters from s2 to s1
    char* str1 = (char*)s1;
    const char* str2 = (const char*)s2;
 
    for (; 0 < n; str1++, str2++, n--)
        *str1 = *str2;
    return (s1);
}
 
int main()
{
    char str1[32] = "";
    char str2[32] = "c programming";
         
    memcpy_implementation(str1, str2, 5);
 
    puts(str1);
 
    return 0;
}
 
 
 
 
/*
run:
     
c pro
     
*/

 



answered Jun 3, 2023 by avibootz

Related questions

1 answer 140 views
140 views asked Sep 20, 2021 by avibootz
1 answer 272 views
272 views asked Jan 26, 2016 by avibootz
1 answer 180 views
180 views asked Jan 26, 2016 by avibootz
1 answer 85 views
85 views asked Jun 10, 2025 by avibootz
1 answer 132 views
...