目录
1、memset
- 作用:将一段内存区域设置为指定的值。
- 函数接口:
void *memset(void *ptr, int value, size_t num)
- 参数介绍:
ptr
:指向要设置值的内存起始地址的指针。value
:要设置的值(以整数形式表示)。num
:要设置的字节数。使用示例:
#include <stdio.h> #include <string.h> int main() { char str[20]; memset(str, 'A', sizeof(str)); // 将 str 的所有字节设置为 'A' printf("%s\n", str); return 0; }
模拟实现:
void *my_memset(void *ptr, int value, size_t num) { unsigned char *p = (unsigned char *)ptr; // 将指针类型转换为无符号字符型指针 for (size_t i = 0; i < num; ++i) { p[i] = value; // 设置每个字节为指定的值 } return ptr; }
2、memcpy
- 作用:将一段内存区域的内容复制到另一段内存区域。
- 函数接口:
void *memcpy(void *destination, const void *source, size_t num)
- 参数介绍:
destination
:指向目标内存区域的指针,即要复制到的位置。source
:指向源内存区域的指针,即要复制的内容的起始位置。num
:要复制的字节数。使用示例:
#include <stdio.h> #include <string.h> int main() { char source[] = "Hello, World!"; char destination[20]; memcpy(destination, source, sizeof(source)); // 将 source 复制到 destination printf("%s\n", destination); return 0; }
模拟实现:
void* my_memcpy(void* destination, void* source, size_t num) { while (num--) { *(char*)destination = *(char*)source; ++(char*)destination; // 注意:后置 ++ 不可以,因为强制类型转换仅存在于当前表达式。 //最佳表达式为:destination = (char*)destination + 1; // 前置 ++ 在部分编译器或cpp文件中会报错 ++(char*)source; } }
3、memmove
- 作用:将一段内存区域的内容复制到另一段内存区域,两段内存区域可以重叠。
- 函数接口:
void *memmove(void *destination, const void *source, size_t num)
- 参数介绍:
destination
:指向目标内存区域的指针,即要复制到的位置。source
:指向源内存区域的指针,即要复制的内容的起始位置。num
:要复制的字节数。使用示例:
#include <stdio.h> #include <string.h> int main() { char str[] = "Hello, World!"; memmove(str+7, str, strlen(str)+1); // 将字符串前 7 个字符移到后面 printf("%s\n", str); return 0; }
模拟实现:
void* my_memmove(void* destination, void* source, size_t num) { if (destination > source) { while (num--) { *(char*)destination = *(char*)source; ++(char*)destination; ++(char*)source; } } else { for (int i = num - 1; i >= 0; i--) { *((char*)destination + i) = *((char*)source + i); } } }
memcpy与memmove的区别:
memmove函数处理的源内存块和目标内存块是可以重叠的。 如果源空间和目标空间出现重叠,就得使用memmove函数处理。
4、memcmp
- 作用:比较两段内存区域的内容是否相同。
- 函数接口:
int memcmp(const void *ptr1, const void *ptr2, size_t num)
- 参数介绍:
ptr1
:指向第一个内存区域的指针。ptr2
:指向第二个内存区域的指针。num
:要比较的字节数。使用示例:
#include <stdio.h> #include <string.h> int main() { char str1[] = "Hello"; char str2[] = "Holly"; int result = memcmp(str1, str2, sizeof(str1)); if (result == 0) { printf("Strings are equal.\n"); } else { printf("Strings are not equal.\n"); } return 0; }
模拟实现:
int my_memcmp(const void *ptr1, const void *ptr2, size_t num) { const unsigned char *p1 = (const unsigned char *)ptr1; const unsigned char *p2 = (const unsigned char *)ptr2; for (size_t i = 0; i < num; ++i) { if (p1[i] < p2[i]) { return -1; // p1 < p2 } else if (p1[i] > p2[i]) { return 1; // p1 > p2 } } return 0; // p1 == p2 }