22.0、C语言——内存函数的剖析和使用
那么在使用内存函数的时候引入头文件 <string.h> 或 <memory.h> 头文件;
memcpy ( )
void* memcpy ( void* destination , const void* source , size_t num );
1. 函数 memcpy() 从 source 的位置开始向后复制 num 个字节的数据到 destination 的内存位置;
2. 这个函数在遇到 ' \0 ' 的时候并不会停下来;
3. 如果 source 和 destination 有任何的重叠,复制的结果都是未定义的;【比如:int arr[] = {1,2,3,4,5,6,7,8,9,10}; memcpy(arr+2,arr+4,16);那么数据重叠了导致无法正常拷贝;】
4. 内存拷贝函数 memcpy() 可以拷贝任何数据类型,而 strcpy()函数 只能拷贝字符串类型的数据;
自定义模拟实现 my_memcpy() 函数,代码如下::
char* my_memcpy(void* dest,const void* source,unsigned int num) {
assert(dest && dest);
void* ret = dest;
while (num--) {
*(char*)dest = *(char*)source;
((char*)dest)++;
((char*)source)++;
}
return ret;
}
memmove ( )
void* memmove ( void* destination , const void* source , size_t num );
1. 在上面的 memcopy( ) 函数说道 -> 如果拷贝的数据内存发生重叠则无法正常拷贝,那其实 memmove ( ) 函数就是来解决这个问题的;
自定义模拟实现 my_memmove() 函数,代码如下:
char* my_memmove(void* dest,const void* source,unsigned int num) {
assert(dest && dest);
void* ret = dest;
int flag = num;
//1.source 在 dest 前面,就从后往前 copy
if(source < dest) {
while(flag--) {
*((char*)dest + num-1) = *((char*)source + num-1);
((char*)dest)--;
((char*)source)--;
}
}
//2.source 在 dest 后面,就从前往后 copy
else {
while (flag--) {
*(char*)dest = *(char*)source;
((char*)dest)++;
((char*)source)++;
}
}
return ret;
}
memcmp ( )
int memcmp ( const void* ptr1,cosnt void* ptr2 , size_t num );
1. 比较从 ptr1 和 ptr2 指针开始的 num 个字节【num 是字节数】;
2. 返回值如下:
Retuen value
———————————————————————————————————————————
returns an integral value indicating the relationship between the content of the memory blocks:
| return value | indicates |
|---|---|
| < 0 | the first byte that does not match in both memory clocks has a lowe value in ptr1 than in ptr2 ( if evaluated as unsigned char values ) |
| 0 | the contents of both memory blocks are equal |
| > 0 | the first byte that does not match in both memory blocks has a greater value in ptr1 in ptr2 ( if evaluated as unsigned char values ) |
3. 和 strcmp() 函数比较的方式差不多,一 一 对比,直到对比到两个不同的元素,或者对比完 num 个字节;
比如 -> int ptr1[] = {1,2,3,4,5}; int ptr2[] = {1,2,7,4,5}; memcmp( ptr1 , ptr2 , 12); 那么在 vs 编译器下 返回的值是 -1 ;
memset ( )
内存设置函数 ->
void* memset ( void* dest , int c , size_of count );
实例代码,如下所示:
int main() {
char str[10] = { 0 };
memset(str, '#', 9);
printf("%s",str);
return 0;
}
初始化一个 10 个字节的字符数组,再用 memset() 函数将该数组的前 9 个字节改成 ' # '
memset() 函数可以把 任何类型的任何数据 修改成 -> 任何类型的任何数据,但是注意 -> 每次修改的内存空间大小为 1 字节;
4074

被折叠的 条评论
为什么被折叠?



