在 C 语言中,有一组内存函数可以用来操作内存,这些函数通常以 "mem" 开头。
以下是一些常用的内存函数和它们的使用方法:
- memcpy(dest, src, n) 用于将源内存区域的前 n 个字节复制到目标内存区域,如果目标和源内存区域重叠,则不能保证复制的顺序。
示例代码:
char src[] = "hello";
char dest[10];
memcpy(dest, src, sizeof(src));
printf("%s\n", dest);
输出: hello
- memset(ptr, value, n) 用于设置内存区域的前 n 个字节的值为特定的值。
示例代码:
char str[50] = "hello world";
memset(str, '*', 3);
printf("%s\n", str);
输出: ***lo world
- memcmp(ptr1, ptr2, n) 比较两个内存区域的前 n 个字节。函数返回值为 0 表示两个区域相同,返回值为正数表示第一个不相同的字节在 ptr1 中的 ASCII 码值大于在 ptr2 中的 ASCII 码值,返回值为负数表示相反。
示例代码:
char s1[] = "hello";
char s2[] = "world";
if (memcmp(s1, s2, sizeof(s1)) == 0) {
printf("s1 and s2 are equal\n");
} else {
printf("s1 and s2 are not equal\n");
}
输出: s1 and s2 are not equal
- memmove(dest, src, n) 与 memcpy 函数类似,用于将源内存区域的前 n 个字节复制到目标内存区域。不同之处在于,如果目标和源内存区域重叠,则此函数仍然保证复制的顺序。
示例代码:
char str[] = "hello world";
memmove(str + 6, str, 5);
printf("%s\n", str);
输出: world world
以上是一些常用的内存函数及其使用方法,可以帮助程序员更方便地操作内存区域。