求教一个简单的C语言题目..

题目是:设计并测试一个函数,其功能是搜索由函数的第一个参数指定的字符串,在其中查找由函数的第二个参数指定的字符的第一次出现的位置。如果找到,返回指向这个字符的指针:如果没有找到,返回空字符(这种方式和 strchr()函数的功能一样)。在一个使用循环语句为这个函数提供输入的完整程序中进行测试。

我的代码
#include
#include
#define QUIT "quit"
#define SIZE 80
//搜索字符在字符串中首次出现的位置
char * str_ch(char * str, char c);

int main(void)
{
char str[SIZE];
char ch;
char * ret_val;

printf("Input a string (type quit to quit):\n");
gets(str);
while (strcmp(str, QUIT))
{
    printf("Input a character: ");
    scanf("%c", &ch);
    while (getchar() != '\n')       //跳过剩余输入部分
        continue;
    ret_val = str_ch(str, ch);
    if (ret_val != NULL)
        printf("Find! The string start with the %c:\n"
        "%s\n", ch, ret_val);
    else
        printf("Can't find!\n");
    printf("Input a string (type quit to quit):\n");
    gets(str);
}
printf("Bye.\n");

return 0;

}

char * str_ch(char * str, char c)
{
int flag = 0;

while (str)
    if (*str++ == c)
    {
        flag = 1;
        break;
    }
if (flag)
    return str - 1;
else
    return NULL;

}

当字符串中有该字符时,输出的结果完全正确,
但是当字符串中没有该字符时,就出现错误。
想了半天还是没看出来。。

http://blog.csdn.net/candice_blanche/article/details/54833681

语法错误还是逻辑错误?

while(str),没有字符的时候if(*str++==c)永远不成立,感觉进入死循环了。直到str到一个正好是false的地址才能退出循环。
是否应修改为,多一个str的长度做循环,或者str里边有个结束字符最为退出条件。

/*bjjoy2009 说的对,你的while判断有问题。试一下改写后的这个函数的。*/

char * str_ch(char * str, char c)
{
int flag = 0;
int iLenth = strlen(str); //字符串长度
int j = 0; //记录比对位置
while (j<iLenth) //比对到字符串最后位置还没有找到字符时退出循环
if (*str++ == c)
{
flag = 1;
break;
}
else
{
j++; //当前位置字符不是要找的字符,位置往后移动一位

if (flag)
return str - 1;
else
return NULL;
}