C语言内存函数
注意: 使用这些函数需要包含
string.h
头文件。
1. memcpy
void * memcpy ( void * destination, const void * source, size_t num );
- 从
source
指向的位置开始,向后复制num
个字节的内容到destination
中。 - 复制过程中,不在乎内容是什么,无论是什么内容都是照搬。
destination
和source
指向的空间中有任何的重叠部分,那么它们复制的结果都是未定义的。- 需要注意的是,在拷贝字符串时,如果拷贝的内容最后一个位置不是
\0
,最好在拷贝结束后加上\0
,否则后期可能造成越界访问。
#include <stdio.h>
#include <string.h>
int main()
{
char* s1 = "hello memcpy";
char s2[50];
memcpy(s2, s1, ((strlen(s1) + 1) * sizeof(s1[0])));
printf("%s\n", s2);
return 0;
}
2. memmove
void * memmove ( void * destination, const void * source, size_t num );
- 和
memcpy
不同的是memmove
的destination
和source
指向的部分是可以重叠的。
#include <stdio.h>
#include <string.h>
int main()
{
char s1[100] = "hello memmove 123456789";
memcpy(s1 + 14, s1, 13 * sizeof(s1[0]));
printf("%s\n", s1);
return 0;
}
3. memset
void * memset ( void * ptr, int value, size_t num );
- 将
ptr
指向的内存的num
个字节的内存全部设置成value
。
#include <stdio.h>
#include <string.h>
int main()
{
char s1[100] = "hello memset";
memset(s1, 'C', 3);
printf("%s\n", s1);
return 0;
}
4. memcmp
int memcmp ( const void * ptr1, const void * ptr2, size_t num );
- 比较
ptr1
和ptr2
指向的位置开始,向后的num
个字节的内容。 - 如果
ptr1
指向的内容小于ptr2
指向的内容,则返回值<0
。 - 如果
ptr1
指向的内容等于ptr2
指向的内容,则返回值==0
。 - 如果
ptr1
指向的内容大于ptr2
指向的内容,则返回值>0
。
#include <stdio.h>
#include <string.h>
int main()
{
char s1[] = "123456789";
char s2[] = "234567890";
printf("%d\n", memcmp(s1, s2, 5 * sizeof(char)));
return 0;
}