我的strchr版本出了什么问题?

时间:2012-07-08 21:05:18

标签: c pointers strchr

我的任务是编写我自己的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
            }
}

4 个答案:

答案 0 :(得分:4)

返回最初初始化为字符串开头的“点”,此后不再移动。你根本不需要那个变量,但可以简单地返回& s [dog](虽然我更喜欢比dog更具描述性的变量名)。

事实上,你可以通过这样简单的事情生存下来:

while (*s != c && *s)
    ++s;

return (*s == c) ? s : NULL; 

答案 1 :(得分:4)

您正在尝试将地址存储到point,但它是一个int变量。你应该这样做:

char *strchr(char *s, char c) {
    int pos = 0;
    while (s[pos] != c && s[pos] != '\0')
        pos++;
    if (s[pos] == c)
        return &s[pos];
    else
        return NULL;
}

顺便说一下:s应该char *而不是const char *,因为你返回指向char的指针,这不是一个好的风格;)(或者返回const char *

答案 2 :(得分:0)

int point;

这不是指针的声明,这里是如何声明指向int的指针:

int *bla;

在您的情况下,&s[dog]是指向const char的指针,因此您希望以这种方式声明point

 const char *point;

正如其他人指出的那样,事实上你实际上忽略了你的函数中的这个指针。

答案 3 :(得分:0)

在您的代码中

int point; //this is the pointer to the location given by the index
point = &s[dog];

,当你

时,你正试图将指向char的指针转换为int
char* point = &s[dog];

是你想要的。您应该从函数的返回类型中看到这一点。您想返回char*,但返回int(您的变量point)或NULL。由于您实际上从未真正更改point,因此您实际上是返回数组中第一个字符的地址,因此您的代码无论如何都无法正常工作。 如果您坚持这样做,那么最好使用

char* point = &s[dog];
while ((*point != c) && (*point != '\0')) {          
   ++point;
}
return (*point == c) ? point : NULL;

但是在这里看起来您仍然有一个概念性问题,因为您想要将charint进行比较。如果需要int数组或char数组,则应该计算出来。如果您需要char数组,请将输入参数c更改为char类型。