该代码在许多地方显示“无效的间接”.Please帮助。
int main()
{
char *s1,*s2,*position;
printf("Enter string:\n");
gets(s1);
printf("Enter word to find:\n");
gets(s2);
*position=ststr(*s1,*s1);
if(*position)
printf("word is found at %c loc\n",*position);
else
printf("word not found");
getch();
return 0;
}
char *strstr(char *s1,char *s2)
{
int flag=1;
char i,j;
for(i=0; ;i++)
{
if(*s1[i]==*s2[0])
for(j=i;*s2;j++)
{
if(*s1[j]!=*s2[j])
flag=0;
}
}
if(flag)
return i;
else
return 0;
}发布于 2010-08-24 22:02:42
首先,main中的s1和s2没有被初始化为指向任何有意义的地方。要么将它们声明为静态数组,要么在运行时使用malloc()或calloc()为它们分配内存
#define SIZE 20 // or some number big enough to hold your input
...
char s1[SIZE], s2[SIZE], *position; // s1 and s2 declared statically其次,千万不要使用gets();它会在你的程序中引入一个故障点。请改用fgets():
if (fgets(s1, sizeof s1, stdin) != NULL)
// process s1
else
// check for EOF or error on read编辑
正如其他人所指出的,您在strstr()函数中的比较需要是
*s1 == *s2或
s1[i] == s2[i]但是首先你需要在main中正确地分配你的缓冲区。
发布于 2010-08-24 21:58:44
if(*s1[i]==*s2[0])我的gcc就是这样一个抱怨的例子:
error: invalid type argument of ‘unary *’ (have ‘int’)如果s1是指向char的指针,则s1[i]是一个字符。所以你不能(用*) dereference它了,也就是说s1[i]不再指向任何东西了。
试一试
if(s1[i]==s2[0])而不是。
您还应该更改strstr的返回值:返回一个整数,其中声明返回指向字符的指针。因此,请尝试返回s1+i。
这里有:
for(j=i;*s2;j++)可能不是你想要的。您并没有在循环中的任何地方推进指针s2,实际上,您只是在测试s2[0] (与*s2相同)在每次迭代中是否为零。如果s2不是空字符串,则此循环永远不会终止。
发布于 2010-08-24 22:00:27
我注意到的一个问题是每当您执行*s1[j]时。星号正在取消对数组的引用,[]表示法也是如此。
s[i]实际上意味着*(s + i),所以您不必再次取消对它的引用。你使用它的方式应该读取**(s + i),因为它是一个单一的指针,所以你不能这样做。
https://stackoverflow.com/questions/3557178
复制相似问题