//NULL - '\0'
//Nul - '\0'
#include<stdio.h>
#include<assert.h>
char* my_strcat(char* dest, const char* src)
{
char* ret = dest;
assert(dest != NULL);
assert(src != NULL);
//1.找到dest添加位置 即\0处
while (*dest)//跳到\0处跳出
{
dest++;
}
//2.拷贝数据
while (*dest = *src)//把\0也拷贝过去
{
dest++;
src++;
}
return ret;//方便链式访问
}
int main()
{
char arr1[20] = "hello ";
//my_strcat(arr1, "world");
printf("%s\n", my_strcat(arr1, "world"));
return 0;
}
输出结果:
int main()
{
char arr1[20] = "hello ";
strcat(arr1, arr1);//代码会挂掉
return 0;
}
结论:strcat不能给自己追加
错误方式:
注意:在其它系统不兼容,vs上定义为-1,0,1。应该分为>0,<0,=0的情况。
#include<stdio.h>
#include<assert.h>
#include<string.h>
int my_strcmp(const char*s1, const char*s2)
{
assert(s1 != NULL);
assert(s2 != NULL);
while (*s1 == *s2)
{
if (*s1 == '\0')
{
return 0;
}
s1++;
s2++;
}
return *s1 - *s2;
}
int main()
{
int ret = my_strcmp("abc", "qwe");
if (ret > 0)
{
printf("大于\n");
}
if (ret == 0)
{
printf("等于\n");
}
if (ret < 0)
{
printf("小于\n");
}
return 0;
}
输出结果:
库文件源码位置:
int main()
{
char arr1[20] = {
0 };
char arr2[] = "hello world";
strncpy(arr1, arr2, 5);
printf("%s\n", arr1);
return 0;
}
输出结果:
int main()
{
char arr1[