gpt4 book ai didi

c - 我的 strchr 版本有什么问题?

转载 作者:行者123 更新时间:2023-11-30 20:45:00 24 4
gpt4 key购买 nike

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

最佳答案

您正在尝试将地址存储到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 *)

关于c - 我的 strchr 版本有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11386698/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com