众所周知,下册比上册难
我们今天要实现的函数是:
Strcmp();字符串比较函数
Memcpy();复制函数
memmove();可重叠复制函数
int Strcmp(const char* a, const char* b){
assert(a != NULL && b != NULL);
if (*a == '\0'&& *b == '\0'){ return 0; }
if (*a == '\0'&& *b != '\0'){ return -1; }
if (*a != '\0'&&*b == '\0'){ return 1; }
while (*a != '\0' && *b != '\0'){
if (*a > *b){
return 1;
}
else if (*a < *b){
return -1;
}
else { ++a; ++b; }
}
return 0;
}
``
void *Memcpy(void *destin,const void *source, unsigned n){
assert(destin != NULL && source != NULL);
char* p1 = (char*)destin;
char* p2 = (char*)source;
while (n--){
*p1 = *p2;
++p1;
++p2;
}
//printf("%s\n", destin); 测试代码,原数组为数字也可;
return destin;
}
``
void *Memmove(void * dest, const void *src, int count)
{
assert(dest != NULL && src != NULL);
char* p1 = (char*)dest;
char* p2 = (char*)src;
if (dest > src){
while (count--){
*(p1 + count) = *(p2 + count);
}
printf("1\n");
}
else {
while (count--){
*p1 = *p2;
p1++;
p2++;
}
}
return dest;
}
``
需要注意的是:最后两个函数里面的数字为,你要复制的字节空间大小!!!
切记,切记,切记。
因为本来你的指针并没有大小,我们强制转化为了char*,这每加+便是1字节,所以你的数字必须是空间大小
举例:
int a[4]={1,2,3,4};
memmove(a,a+1,8);
输出结果2,3,3,4
后面那个8表示2个int即两位数。
再比如:
char a[]="test";
memmove(a,a+1,2);
输出结果:esst
这里因为字符串的单字符大小为1字节,所以输出这样。