How to implement the memmove function in C

1 Answer

0 votes
#include <stdio.h>

void* memmove(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;

	if (str2 < str1 && str1 < str2 + n)
		for (str1 += n, str2 += n; 0 < n; n--)
			*--str1 = *--str2; // backward copy 
	else
		for (; 0 < n; n--)
			*str1++ = *str2++; // forward copy
	return s1;
}

int main()
{
	char str1[16] = "";
	char str2[16] = "c programming";
		
	memmove(str1, str2, 5);

	puts(str1);

	return 0;
}




/*
run:
    
c pro
    
*/


 



answered Dec 17, 2022 by avibootz

Related questions

1 answer 194 views
1 answer 209 views
1 answer 85 views
85 views asked Jun 10, 2025 by avibootz
1 answer 132 views
1 answer 130 views
1 answer 100 views
100 views asked Aug 2, 2024 by avibootz
...