目錄
一、前言
二、 memmove和memcmp函式
1.memmove函式(記憶體移動)
函式的使用:
memmove函式的模擬實作
2、memcmp函式(記憶體比較)
函式的使用:
一、前言
前面我們已經講了memcpy和memset函式的使用,相信小伙伴們對這兩個函式已經
非常熟悉了,(如果還不是很熟悉,可以看看上篇)那么我們現在要學習另外兩個函式
memmove和memcmp,
本章內容memmove和memcmp函式
二、 memmove和memcmp函式
1.memmove函式(記憶體移動)
函式引數形式:void*memmove(void*destination,const void*source,size_t num);
其中num是無符號的整數,單位是位元組,memcpy函式不能實作重復部分的拷貝,
如在同一個陣列中無法實作,但是memmove可以實作重復記憶體拷貝,也可以說
memcpy是memmove的子集,
函式的使用:
#include<stdio.h>
#include<string.h>
int main()
{
int arr1[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
memmove(arr1,arr1+2,20);
for (int i = 0; i < 10; i++)
{
printf("%d ", arr1[i]);//34567678910
}
return 0;
}
memmove函式的模擬實作
#include<stdio.h>
#include<assert.h>
void*my_memmove(void*dest, const void*src, size_t num)
{
assert(dest&&src);
void*ret = dest;
if (dest < src)
{
while (num--)
{
*(char*)dest = *(char*)src;
++(char*)dest;
++(char*)src;
}
}
else
{
while (num--)
{
*((char*)dest + num) = *((char*)src + num);
--(char*)dest;
--(char*)src;
}
}
return ret;
}
int main()
{
int arr1[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
my_memmove(arr1, arr1+2, 5 * sizeof(int));
for (int i = 0; i < 10; i++)
{
printf("%d", *(arr1 + i));//34567678910
}
return 0;
}
2、memcmp函式(記憶體比較)
memcpy函式引數形式int memcmp(const void *str1,const void* str2,size_t num);
這個函式的回傳型別是int ,nu單位是位元組(一個int 4位元組),str1大于str2回傳一個
大于0的數,str1小于str2則回傳一個小于0的數,等于則回傳0,
#include<stdio.h>
#include<string.h>
int main()
{
int arr1[10] = { 1, 2, 3, 4, 5, 6, 7 };
int arr2[10] = { 1, 2, 3, 4, 5, 8, 9 };
int kc = memcmp(arr1, arr2, 20);
printf("%d", kc);
return 0;
}
注意:本電腦是小端存盤模式(以后會講),簡單的說就是高位存高地址,大端則相反如1為
00000001,小端模式下為01000000,
簡單的說一下:如圖

所以說在整形陣列比較非一個整數的位元組大小端就有區別了
在小端中:
#include<stdio.h>
#include<string.h>
int main()
{
int arr1[10] = { 1, 2, 3, 4, 5, 6, 7 };
int arr2[10] = { 1, 2, 3, 4, 5, 8, 9 };
int kc = memcmp(arr1, arr2, 21);
printf("%d", kc);
return 0;
}
結果是一個小于0的數,vs編輯器默認是-1,原因在于前面20個位元組相同,但是第21個位元組,
如圖:

所以arr1小于arr2,回傳小于0的數,如果是大端就不一樣了,這里就不說那么多了,下次會涉及,
這期結束了,兄弟們一鍵三連
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/300515.html
標籤:其他
上一篇:計算機中整數的存盤與大小端
