【发布时间】:2012-07-08 21:05:18
【问题描述】:
我的任务是编写我自己的 strchr 版本,但它似乎不起作用。任何建议将不胜感激。 这里是:
char *strchr (const char *s, int c) //we are looking for c on the string s
{
int dog; //This is the index on the string, initialized as 0
dog = 0;
int point; //this is the pointer to the location given by the index
point = &s[dog];
while ((s[dog] != c) && (s[dog] != '\0')) { //it keeps adding to dog until it stumbles upon either c or '\0'
dog++;
}
if (s[dog]==c) {
return point; //at this point, if this value is equal to c it returns the pointer to that location
}
else {
return NULL; //if not, this means that c is not on the string
}
}
【问题讨论】:
-
“似乎不起作用” - 请描述得更详细。
-
嗯,一个问题是你命名一个变量
dog没有特别的原因。第二个似乎是你混合了指针和整数。 -
point不是指针类型,所以不能保存指针。这段代码甚至不应该编译。此外,int不是字符串中偏移量的合适类型。 -
@larsmans:也许它类似于 OP 对
strcat的实现中的cat...? :-)