我是寫字符串檢索。但是如果把jiansuo()這個函數中第二個if(cha(p2)==(p3-p2+1))的話就沒問題了。也就是說後邊不能==i,如果是i的話,就出錯~~
#include
int cha(char *p1)
{
int num=0;
for (char *p = p1; *p!= '\0'; p++)
{
num++;
}
return num;
}
void jiansuo(char *p1,char *p2)
{
for (char *p = p1; p<(p+cha(p1)-cha(p2)); p++)
{
int i = 0;
for (char *p3 = p2; *p3 != '\0'; p3++,i++)
{
if (*p3 != *(p+(p3-p2)))
{
break;
}
if (cha(p2)== i)
{
printf("找到了!在第%d個",p-p1+1);
return;
}
}
}
printf("沒找到\n");
}
void main()
{
char *o = "tiandiwuji";
char *a = "diwu";
jiansuo(o,a);
getchar();
}
有兩個問題:
1.for (char *p = p1; p<(p+cha(p1)-cha(p2)); p++)應該改成for (char *p = p1; p<(p1+cha(p1)-cha(p2)); p++)
不然的話p<(p+cha(p1)-cha(p2))相當於p<p+6肯定恆滿足啊,直到越界崩潰
2.if (cha(p2)== i )改成if (cha(p2)== i + 1)因為i++是在當次for循環之後才執行的,只要之前沒有break說明當前字符是相等的
#include <stdio.h>
#include <string.h>
int cha(char *p1)
{
int num=0;
for (char *p = p1; *p!= '\0'; p++)
{
num++;
}
return num;
}
void jiansuo(char *p1,char *p2)
{
for (char *p = p1; p<(p1+cha(p1)-cha(p2)); p++)
{
int i = 0;
for (char *p3 = p2; *p3 != '\0'; p3++,i++)
{
if (*p3 != *(p+(p3-p2)))
{
break;
}
if (cha(p2)== i + 1)
{
printf("找到了!在第%d個",p-p1+1);
return;
}
}
}
printf("沒找到\n");
}
void main()
{
char *o = "tiandiwuji";
char *a = "diwui";
jiansuo(o,a);
getchar();
}