findString函数返回错误的值

时间:2014-06-30 04:51:07

标签: c string

使用以下代码:

#include    <stdlib.h>
#include    <stdio.h>

/* 
 * ===  FUNCTION  =========================================================
 *         Name:  findString
 *  Description:  Determines if one character string exists inside other
 *                string. If found, returns location in source string. If
 *                not, returns -1.
 * ========================================================================
 */

int  findString ( const char  source[], const char  search[] )
{
    int  i, j;

    for ( i = 0; source[i] != '\0'; i++ )
        for ( j = 0; source[i + j] == search[j]; j++ ) 
            if ( search[j] == '\0' )
                return i;

    return -1;
}       /* -----  end of function findString  ----- */

/* 
 * ===  FUNCTION  =========================================================
 *         Name:  main
 *  Description:  Displays result of findString function.
 * ========================================================================
 */

int  main ( void )
{
    const char  source[] = "hello, world";
    const char  search[] = "lo, ";
    int  findString ( const char source[], const char search[] );

    printf ( "searching \"%s\" in \"%s\" returns %d.\n", 
            search, source, findString ( source, search ) );

    return EXIT_SUCCESS;
}           /* ----------  end of function main  ---------- */

我希望函数findString函数返回3,但它返回-1。运行gdb时,源字符串打印&#34; hello,world&#34;并搜索打印&#34; lo,&#34;。但是一旦我进入findString函数,源字符串就会打印出#34; lo,&#34;并且搜索字符串打印&#34; hello,world&#34;。他们为什么要换班?

1 个答案:

答案 0 :(得分:3)

因为这个测试失败了

source[i + j] == search[j]
在您有机会询问

之前,在嵌套的for循环中执行

if ( search[j] == '\0' )

因此,在j == 4(且search[j] == '\0'为真)的示例中,第一个测试将失败(因为source[i + j] ==&#39; w&#39; )最终-1将返回。