下列给定程序中,函数proc()的功能是:计算str所指字符串中含有t所指字符串的数目,并作为函数值返回。
请修改程序中的错误,使它能得出正确的结果。
注意:不要改动main()函数,不得增行或删行,也不得更改程序的结构。
试题程序:
#include<stdlib.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>
#define M 80
int proc(char*str。char*t)
{
int n;
char*P,*r;
n=0:
while(*str)
{
p=str:
//****found****
r=p ;
while(*r)
if(*r==*p){r++;p++;}
else break;
//****found****
if(*r==0)
n++:
str++:
}
return n;
}
void main()
{
char str[M3,b[M];int m;
system("CLS");
prinff("\nPlease enter string str:");
gets(str);
printf("\nPlease t·nter substring b:");
gets(b):
m=proc(str,b);
printf("\nThe result is:m=%d\n",m);
}
参考答案
答案解析
(1)错误:r=p;
正确:r=t;
(2)错误:if(*r=0)
正确:if(*r=='\0')
【解析】由于后面的语句控制变量r是指向字符串t的指针,而不是指向字符串str的指针,因此,“r=P;’’应改为“r =t;”。while循环结束后,如果r指向字符串t的结束符,证明字符串str中包含一个t字符串,因此,“if(*r=0),,应改为“if(*r=='\0')”。