我编写了关于串的程序,想要实现在主串中是否有字符串与子串匹配的功能。运行的结果正确,可是每次结果后面都有null pointer assignment,我检查一晚上还是查不出在哪里出错,不知有哪位好心人帮我解答。
程序代码:
#include<malloc.h>
#include<string.h>
#include<stdio.h>
typedef struct
{char *str;
int length;
}string;
strassign(string *s,char *chars)
{int i,j;
if(s->str) free(s->str);
i=strlen(chars);
if(!i)
{s->str=0;s->length=0;}
else
{s->str=(char *)malloc(i*sizeof(char));
if(!s->str) printf("error");
for(j=0;j<i;j++)
s->str[j]=chars[j];
s->length=i;
}
}
int indexFL(string *s,string *t,int pos)
{int i,j,k;
int slength,tlength;
char patstartchar,patendchar;
slength=s->length;tlength=t->length;
i=pos;
patstartchar=t->str[0];
patendchar=t->str[t->length-1];
while(i<=slength-tlength)
{if(s->str[i]!=patstartchar) ++i;
else if(s->str[i+tlength-1]!=patendchar) ++i;
else
{k=1;j=1;
while(j<tlength-1 && s->str[i+k]==t->str[j])
{++k;++j;}
if(j==tlength-1) return i+1;
else ++i;
}
}
return 0;
}
void strprint(string *s)
{int i;
for(i=0;i<s->length;i++)
printf("%c",s->str[i]);
printf("\n");
}
main()
{string *s,*t;
char char1[100],char2[100];
int pos;
printf("\nInput father string:");
gets(char1);
strassign(s,char1);
printf("\nInput child string:");
gets(char2);
strassign(t,char2);
printf("\nPos=");
scanf("%d",&pos);
printf("\nThe father string:");
strprint(s);
printf("\nThe child string:");
strprint(t);
printf("\nThe position:%d",indexFL(s,t,pos));
}