C语言内存函数
memcpy
包含在头文件<string.h>中
语法格式
1 | void * memcpy ( void * destination, const void * source, size_t num ); |
从 source 的位置开始拷贝 num 个字节的数据到 destination 指向的位置
1
2
3
4
5
6
7
8//memcpy 针对内存块进行拷贝
int arr1[] = { 1,2,3,4 };
int arr2[4] = { 0 };
memcpy(arr2, arr1, 4 * sizeof(int));
for (int i = 0;i < 4;i++)
{
printf("%d ", arr1[i]);
}
遇到 ‘\0’ 不会停下来
如果 destination 和 source 有任何的重叠,拷贝的结果是未定义的
1
2
3
4
5
6
7
8
9
10// 如果 destination 和 source 有任何的重叠,拷贝的结果是未定义的
int arr1[10] = { 1,2,3,4,5,6,7,8,9,10 };
// 这里拷贝空间出现了重叠
memcpy(arr1 + 2, arr1, 4 * sizeof(int));
for (int i = 0;i < 10;i++)
{
// 虽然完成了目标,但是C语言中明确说明了 memcpy 就是用来拷贝不重叠的内存块的,
// 所以不要这么用 memcpy
printf("%d ", arr1[i]);
}
C语言中明确说明了 memcpy 就是用来拷贝不重叠的内存块的, 所以不要这么用 memcpy
模拟实现 memcpy
简单模拟一下 memcpy 的基本功能
1 | void* my_memcpy(void* destination, const void* source, size_t num) |

memmove
包含在头文件 <string.h> 中,与 memcpy 类似,但是支持内存块重叠的拷贝
语法格式
1 | void * memmove ( void * destination, const void * source, size_t num ); |
1 | // memmove 是可以进行内存空间叠加的拷贝 |

memmove 的模拟
1 | void* memmove(void* destination, const void* source, size_t num); |
因为存在内存空间重叠,在进行内存空间拷贝时,核心逻辑就是先从不会影响后
续拷贝的内存空间起进行拷贝
第一种情况: source > destination


第二种情况: source < destination


当 destination 和 source 相同时用 source < destination 一样的拷贝方法,比较
容易就能想到这里不做演示
1 | void* my_memmove(void* destination, const void* source, size_t num) |

memset
包含在头文件 <string.h> 中
语法格式
1 | void * memset ( void * ptr, int value, size_t num ); |
用来设置内存,将内存中的值以字节为单位设置成 value
1 | char str[] = "hello world"; |

memcmp
包含在头文件 <string.h>中
语法格式
1 | int memcmp ( const void * ptr1, const void * ptr2, size_t num ); |
比较从 ptr1 和 ptr2 起向后的 num 个字节
若 ptr1 < ptr2 ,返回 < 0 的值
相等返回 0
若 ptr1 > ptr2 ,返回 > 0 的值
比较依据是指针指向的内容不等时的大小
1 | char buffer1[] = "DWgaOtP12df0"; |

本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 不灭的黄金瞳!



