内存操作函数

118 阅读1分钟

1.内存清空和内存复制函数

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void test()
{
	//1.memset内存设置,主要用于清空内存
	char buf[32] = "hello world";
	printf("buf = %s\n", buf);
	//进行内存清空
	memset(buf, 0, sizeof(buf));
	printf("buf = %s\n", buf);

	//2.memcpy内存复制,
	char dst[64] = { 0 };
	char src[64] = "hello world";

	memcpy(dst, src, sizeof(dst));
	printf("buf = %s\n", dst);
	
	//3.memmove内存移动
	int arr[5] = { 1,2,3,4,5 };

	memmove(arr + 2, arr + 1, 3 * sizeof(int));

	for (int i = 0; i < sizeof(arr)/sizeof(arr[0]); i++)
	{
		printf(" = %d\n", arr[i]);
	}

	//4.memcmp内存比较
	char str1[32] = "hello\0world";
	char str2[32] = "hello\0aaa";

	//字符串比较函数
	if (strcmp(str1, str2))
	{
		printf("字符串比较相同\n");
	}
	else
	{
		printf("字符串比较不同\n");
	}

	//内存比较函数
	if (memcmp(str1, str2, sizeof(str1)))
	{
		printf("内存比较相同\n");
	}
	else
	{
		printf("内存比较不同\n");
	}
}

int main()
{
	test();
	system("pause");
	return 0;
}