c语言中strstr通过指针
这是我制作的 strstr 的标准代码吗???
char* fstrset(char *s,char *t)
{
int b, i=0,j=0;
while(*(s+i)!='\0')
{
if(*(t+j)=='\0')
break;
else if(*(s+i)==*(t+j))
{
i++;j++;b=1;
}
else
{ i++;b=0;j=0;
}
}
if(b==0)
return((char*)NULL);
else if(b==1)
return(s+i-j);
}
is this the standard code for strstr i made????
char* fstrset(char *s,char *t)
{
int b, i=0,j=0;
while(*(s+i)!='\0')
{
if(*(t+j)=='\0')
break;
else if(*(s+i)==*(t+j))
{
i++;j++;b=1;
}
else
{ i++;b=0;j=0;
}
}
if(b==0)
return((char*)NULL);
else if(b==1)
return(s+i-j);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
这就是标准对此的全部规定:
因此,您似乎缺少参数上的
const
限定符。至于样式,请注意,
*(ptr+index)
可以用ptr[index]
替换,并且size_t
是最好使用的类型用于索引指针。至于是否是一种常见的实现方式,与GCC的代码进行比较:
This is all the standard has to say about it:
So, it looks like you're missing
const
qualifiers on arguments.As for style, note that
*(ptr+index)
can be replaced byptr[index]
, andsize_t
is the best type to use for indexing a pointer.As for being a common way to implement it, compare with GCC's code:
你的代码有问题。给定:
fstrset(haystack,needle)
返回错误地返回NULL
。Your code is buggy. Given:
fstrset(haystack, needle)
returns incorrectly returnsNULL
.除了caf提到的bug之外,还有其他的bug:
1)未初始化b。如果
s
指向'\0'
,则可能会到达右大括号,从而省略任何返回语句。2) 如果字符匹配到
s
指向的字符串末尾,则不会检查t
指向的字符串是否也结束。Besides the bug mentioned by caf there are others:
1) Uninitialized b. If
s
points to'\0'
, closing brace may be reached, omitting any return statements.2) If characters match up to the end of string pointed to by
s
there is no check if the string pointed to byt
ends too.这是做什么的?看起来像是胡言乱语。为什么要添加指针并将它们与整数混合?抱歉,但这整件事没有意义。回答你的问题,我不这么认为。但如果你编译它并运行它,那么是的。好吧,当你仔细观察时,你的代码确实有意义。是的,它看起来确实可以编译,如果这就是您所说的标准代码的意思。
What does this do? It looks like gibberish. Why adding pointers, and mixing them with ints? Sorry, but the whole thing doesn't make sense.And to answer your question, i don't think so. But if you compile it and it runs, then yes.Okay, your code does make sense when you look at it closer. Yes, it does look like it will compile, if thats what you mean by standard code.
快速通读似乎表明代码可以工作(可能存在无法工作的边缘情况)。你告诉我们,这有效吗?
但为什么要这么做呢?只需调用 strstr
a quick read through seems to show that the code works (there are probably edge cases that dont work). You tell us, does it work?
But why do it? just call strstr
没有“标准代码”,只有标准结果。
标准 C 库中的任何实现都不太可能使用数组索引,因此您的代码不太可能与逐行细节中的任何实现相匹配。
There is no 'standard code', just the standard result.
It is unlikely that any implementation in a standard C library uses array indexing, so it is unlikely that your code matches any implementation in line-by-line detail.
没有“标准代码”,只有标准结果。
标准 C 库中的任何实现都不太可能使用数组索引,因此您的代码不太可能与行实现中的任何实现相匹配。
There is no "standard code", only standard results.
It is unlikely that any implementation in the standard C library will use array indexes, so your code is unlikely to match any implementation in the line implementation.