C - If/Else和Pointers返回错误的字符串

Kah*_*ahn 1 c string pointers

我们有一个函数最长,它返回由字母组成的最长子字符串.例:

longest("112****hel 5454lllllo454")
Run Code Online (Sandbox Code Playgroud)

会回来:lllllo

但是,当我运行程序时,它似乎返回lllllo454.这是功能:

char *longest(char *s){
    char *pMax = NULL;
    int nMax = 0;
    char *p = NULL;
    int n = 0;
    int inside = 0; //flag
    while(*s!='\0'){
        char c = *s;
        if((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')){
            if(inside == 0){
                n = 1;
                p = s;
                inside = 1;
            }
            else
                n++;
            if(inside == 1){
                if(n > nMax){
                    nMax = n;
                    pMax = p;
                    inside = 0;
                }
            }
        }//end isLetter if
        s++;
    }
    return pMax;
}
Run Code Online (Sandbox Code Playgroud)

这里有一些我没有看到的东西......你们觉得怎么样?

tva*_*son 6

您只是返回指向最长子字符串中第一个字符的指针.实际上,您不会在子字符串结尾之后添加字符串终止符,因此它会继续到原始字符串的末尾.您可能应该将子字符串(仅序列中的那些字符)复制到新字符串并返回指向该字符串的指针.

 char* newStr = malloc(nMax+1);
 strncpy( newStr, pMax, nMax );
 *(newStr+nMax) = '\0';
 return newStr;
Run Code Online (Sandbox Code Playgroud)