1

考虑代码及其结果:

while ((row = mysql_fetch_row (table_info)) != NULL)
{
    answer='\0';
    printf ( "%s: ", row[0] );
    scanf ( "%c", &answer );
    getchar();
    if ( answer == 'y')
    {
        printf ( "*****\n" );
        table_name[index] = malloc ( strlen(row[0]) + 1 );
        printf ( "*****\n" );
        memcpy ( &table_name[index], &row[0], strlen(row[0]) + 1 );
    }
    printf ( "finally inserted: %s \n", table_name[index]);
}

执行结果:

1_time_access: y
*****
*****
finally inserted: 1_time_access 
2_time_access: y
*****
*****
finally inserted: 2_time_access 
39_time_access: y
*****
*****
finally inserted: 39_time_access 

结果解释:row[0]有值1_time_access, 2_time_access, 39_time_access. 现在考虑一种更好的方法,即使用格式字符串来转义\n. 我运行以下代码,但它给出了分离错误,我不明白为什么。代码:

while ((row = mysql_fetch_row (table_info)) != NULL)
{
    answer='\0';
    printf ( "%s: ", row[0] );
    scanf ( "%[^\n]%*c", &answer );
    if ( answer == 'y')
    {
        printf ( "*****\n" );
        fflush(stdout);
        table_name[index] = malloc ( strlen(row[0]) + 1 );
        printf ( "*****\n" );
        fflush(stdout);
        memcpy ( &table_name[index], &row[0], strlen(row[0]) + 1 );
    }
    printf ( "finally inserted: %s \n", table_name[index]);
    fflush(stdout);
}

结果:

1_time_access: y
*****
./set-env.sh: line 17: 15263 Segmentation fault      (core dumped) ./exec dataset_one

(不用担心set-env.sh,这是运行程序的脚本。)

我不明白为什么会这样。

4

1 回答 1

4
if ( answer == 'y')
{
    printf ( "*****\n" );
    fflush(stdout);
    table_name[index] = malloc ( strlen(row[0]) + 1 );
    printf ( "*****\n" );
    fflush(stdout);
    memcpy ( &table_name[index], &row[0], strlen(row[0]) + 1 );
}

                                    /*     BAD      */
printf ( "finally inserted: %s \n", table_name[index]);

你只分配table_name[index]if answer == 'y',但你把它发送给printf不管。我假设这是发生段错误的行。

调试器是你的朋友。它将向您显示变量的状态。

于 2012-06-20T03:10:58.267 回答