【问题标题】:What is wrong with my version of strchr?我的 strchr 版本有什么问题?
【发布时间】: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...? :-)

标签: c pointers strchr


【解决方案1】:

您正在尝试将地址存储到 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 *,因为您返回指向 achar 的指针,这不是一个好的样式;)(或返回 const char *

【讨论】:

  • C 标准要求strchr 采用const 指针,但将一个可变指针返回到同一个缓冲区。因此,一个兼容的纯 C 实现必须放弃 const
  • 你也可以像这样直接增加指针:pastebin.ubuntu.com/1081902
  • 对于pos,您还应该使用size_t,而不是int
【解决方案2】:

您返回“point”,它最初被初始化为字符串的开头并且从那以后没有移动。您根本不需要该变量,但可以简单地返回 &s[dog] (尽管我更喜欢比 dog 更具描述性的变量名)。

事实上,像这样简单的事情你就可以生存:

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

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

【讨论】:

  • +1 返回部分中的if 可以替换为条件运算符以获得更好的紧凑性。
  • +1,尽管此实现中缺少演员表(请参阅我对@wabepper 答案的评论)。
【解决方案3】:
int point;

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

int *bla;

在你的情况下,&s[dog] 是一个指向const char 的指针,所以你想这样声明point

 const char *point;

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

【讨论】:

  • 没错,但 OP 实际上并不需要 int 指针。
【解决方案4】:

在您的代码中

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 类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-16
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 2015-04-06
    • 2014-06-29
    • 2013-09-18
    • 1970-01-01
    相关资源
    最近更新 更多