求解以下有什么错误,为什么比较字符串的会有错误
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
struct OurString {//字符串指针
int Maxm;
int n;
char *pstr;
};
typedef struct OurString* PString;
PString CreateNullString(int);//创建空字符串
void InitString(PString);//初始化字符串
void PrintString(PString);//打印字符串
int SearchString(PString,PString);//比较字符串,返回第一个匹配的索引
int main()
{
int m1,m2,position;
PString hpstr1,hpstr2;
printf("input m1=");
scanf("%d",&m1);
printf("input m2=");
scanf("%d",&m2);
printf("\nNow begin create a null string....\n");
hpstr1=CreateNullString(m1);
hpstr2=CreateNullString(m2);
printf("\nNow begin initialize a string...\n");
InitString(hpstr1);
InitString(hpstr2);
printf("\nNow output a string...\n");
PrintString(hpstr1);
PrintString(hpstr2);
printf("the string1 locate string2 position is:\n");
position=SearchString(hpstr1,hpstr2);
printf("%d\n",position);
return 0;
}
PString CreateNullString(int nn)
{
PString tpstr;
if((tpstr=malloc(sizeof(struct OurString)))==NULL)
{
fprintf(stderr,"mem apply failure!\n");
exit(-1);
}
if((tpstr->pstr=malloc(sizeof(char)*nn))==NULL)
{
fprintf(stderr,"mem apply failure!\n");
exit(-1);
}
tpstr->Maxm=nn;
tpstr->n=0;
return tpstr;
}
void InitString(PString hpstr)
{
int i;
char c;
printf("please input a string, # to quit input:\n");
for(i=0;i<hpstr->Maxm-1;i++)
{
c=getchar();
if(c=='#') break;
hpstr->pstr[i]=c;
hpstr->n++;
}
hpstr->pstr[i]=0;//'\0';
}
void PrintString(PString hpstr)
{
int i;
for(i=0;i<hpstr->n;i++)
printf("%c",hpstr->pstr[i]);
printf("\n");
}
int SearchString(PString t,PString p)
{
int mm=0;
while(j<p1->n-2)
{
for(;mm<p2->n;mm++)
{
if(p1->p[j+mm]!=p2->p[mm])
break;
}
j++;
}
if(j<p1->n-2)
return j;
return -1;
}
[解决办法]
先单步调试
[解决办法]
编译通不过吧.
SearchString中j未声明.
p[j+mm]有可能越界
[解决办法]
楼主,错误有很多吧,不单单只是比较字符串的会有错误
error C2440: '=' : cannot convert from 'void *' to 'struct OurString *'
*' to pointer to non-'void' requires an explicit cast
error C2440: '=' : cannot convert from 'void *' to 'char *'
*' to pointer to non-'void' requires an explicit cast
error C2065: 'j' : undeclared identifier
error C2065: 'p1' : undeclared identifier
error C2227: left of '->n' must point to class/struct/union
fatal error C1903: unable to recover from previous error(s); stopping compilation
[解决办法]
if ((tpstr = (struct OurString *)malloc(sizeof(struct OurString))) == NULL) // 强制转换
if ((tpstr->pstr = (char *)malloc(sizeof(char) * nn)) == NULL) // 强制转换
SearchString里面变量没定义
malloc了之后,没free