C语言实现各种内存操作函数

目录

memcpy(按字节的内存拷贝)

memmove(重叠内存的拷贝)

memcmp(按字节比较大小)

memset(按字节进行初始化)


memcpy(按字节的内存拷贝)

#include 
#include 

void my_memcpy(void* dest, void* str, size_t n)
{
	assert(dest && str);
	void* ret = dest;
	while (n--)
	{
		*(char*)dest = *(char*)str;
		dest = (char*)dest + 1;
		str = (char*)str + 1;
	}
	return ret;
}

int main()
{
	int arr1[5] = { 1,2,3,4,5 };
	int arr2[2] = { 0 };
	my_memcpy(arr2, arr1, 4);//按字节拷贝
	return 0;
}

memmove(重叠内存的拷贝)

#include 
#include 

void* my_memmove(void* dest, const void* str, size_t count)
{
	assert(dest && str);
	void* ret = dest;
	if (dest < str)
	{
		//从前往后拷贝
		while (count--)
		{
			*(char*)dest = *(char*)str;
			dest = (char*)dest + 1;
			str = (char*)str + 1;
		}
	}
	else
		//从后往前拷贝
	{
		while (count--)
		{
			*((char*)dest + count) = *((char*)str + count);

		}
	}
	return ret;
}

int main()
{
	int arr[10] = { 0,1,2,3,4,5,6,7,8,9 };
	my_memmove(arr + 2, arr, 20);//从前往后
	my_memmove(arr, arr + 2, 20);//从后往前

	return 0;
}

memcmp(按字节比较大小)

#include 
#include 

int my_memcmp(void* dest, const void* str, size_t count)
{
	assert(dest && str);
	size_t i = 0;
	for (i = 0; i < count; i++)
	{
		if (*((char*)dest + i) > *((char*)str + i))
		{
			return 1;
		}
		else if (*((char*)dest + i) < *((char*)str + i))
		{
			return -1;
		}
	}
	return 0;
}

int main()
{
	int arr1[] = { 1,2,3,4,5 };
	int arr2[] = { 1,2,3,4,0x11223305 };
	int ret = my_memcmp(arr1, arr2, 20);
	printf("%d\n", ret);
	return 0;
}

memset(按字节进行初始化)

#include 

void* my_memset(void* dest, int n, size_t count)
{
	void* tmp = dest;
	while (count--)
	{
		*(char*)dest = (char)n;
		dest = (char*)dest + 1;
	}
	return tmp;
}

int main()
{
	int arr[] = { 0x11111111,0x22222222,5,6,7,8,9 };
	my_memset(arr, 6, 20);
	int i = 0;
	for (i = 0; i < sizeof(arr) / sizeof(arr[0]); i++)
	{
		printf("%d ", arr[i]);
	}
	return 0;
}

你可能感兴趣的:(C-进阶,c语言,c++)