Mystrcat和StrReverse同时测试就会显示a越界
#define _CRT_SECURE_NO_WARNINGS#include<stdio.h>
#include<string.h>
#include<math.h>
/*
* 1.实现字符串连结.例如"abc","xyz"->"abcxyz"
* void Mystrcat(char *des,const char *src);//des+=src;
* 2.实现字符串比较.例如"abc","x"->小于0的数字;"abc","abbb"->大于0的数字;"abc","abc"->0
* int Mystrcmp(const char *str1,const char *str2);
* 3.实现字符串转数字.例如"12345"->12345;"12a345"->12(遇到非数字字符转换结束);"ab12"->0
* int Myatoi(const char *str);
* 4.实现字符串反转.例如"abc"->"cba";"abcd"->"dcba"
* void StrReverse(char *str);
*/
void Mystrcat(char* des, const char* src)
{
int des_count= 0 , src_count = 0 , i = 0 , j = 0;
while (*(des + i )!= '\0')
{
des_count++;
i++;
}
while (*(src + j ) != '\0')
{
src_count++;
j++;
}
for (i = 0 ; i <= src_count; i++)
{
*(des + i + des_count) = *(src + i );
}
}
int Mystrcmp(const char* str1, const char* str2)
{
for (int i = 0; ; i++)
{
if (*str2 != '\0' && *str1 != '\0'
)
{
if (*str1 > *str2) return 1;//左边大返回正数
else if (*str1 < *str2) return -1;//右边大返回负数
}
else if (*str1 != '\0' && *str2 == '\0') return 1;
else if (*str1 == '\0' && *str2 != '\0') return -1;
else
{
return 0;
}
}
}
int Myatoi(const char* str)
{
int flag = 0 , i =0;
while(*(str + i ) != '\0')
{
if (*(str + i) < '9' && *(str + i) > '0') {
flag = 10 * flag + *(str + i) - '0';
}
else break;
i++;
}
return flag;
}
void StrReverse(char* str)
{
int count = strlen(str) - 1;
int start = 0;
char tmp;
while (start < count)
{
tmp = *(str + start);
*(str + start) = *(str + count);
*(str + count) = tmp;
start++;
count--;
}
}
int main()
{
char a[] = { "asd24dfs" };
char b[] = { "354asdg" };
char c[] = { "123456" };
char d[] = { "sassdg" };
Mystrcat(a, b);
printf("%s\n", a);
Mystrcat(d, c);
printf("%s\n", d);
/*printf("%d\n",Mystrcmp(a, c));
printf("%d\n", Mystrcmp(c, d));
printf("%d\n", Mystrcmp(a, d));
printf("%d\n", Mystrcmp(b, c));*/
/*printf("%d\n", Myatoi(a));
printf("%d\n", Myatoi(b));
printf("%d\n", Myatoi(c));
printf("%d\n", Myatoi(d));*/
StrReverse(a);
printf("%s\n", a);
StrReverse(c);
printf("%s\n", c);
}
C风格字符串依赖 0 作为结束符,strlen也是检测的 \0 ,Mystrcat有添加 \0 ?
页:
[1]