1

我有一段非常简单的代码,它从文件中读取字符。如果索引y从低到高迭代,一切正常。但是,如果它从高到低迭代(注释行),它会给我 seg 错误问题。有人可以解释为什么会这样吗?谢谢!

void read_ct_from_file( unsigned char** ct, const size_t row, const size_t column, FILE* inf ) {
    size_t x, y;
    for( x = 0; x < row; x++ ) {
        for( y = 0; y < column; y++ ) { 
        //for( y = column - 1; y >= 0; y-- ) { // iterate from high to low

              fscanf( inf, "%02x", &ct[x][y] );
              printf( "%02x ", ct[x][y] );
        }
        printf( "\n" );
    }
}
4

3 回答 3

3

size_t是无符号的,所以你的循环将在>= 0之后y = 0继续。max_unsigned

于 2012-06-28T15:53:57.217 回答
0

顺便说一句,拥有无符号 size_t 索引避免环绕下溢的好方法是这种构造:

void read_ct_from_file( unsigned char** ct, const size_t row, const size_t column, FILE* inf ) {
    size_t x, y;
    for( x = 0; x < row; x++ ) {
        for ( y = column; y-- > 0; ) { // iterate from high to low

              fscanf( inf, "%02x", &ct[x][y] );
              printf( "%02x ", ct[x][y] );
        }
        printf( "\n" );
    }
}
于 2012-07-04T10:50:03.443 回答
-1
for( y = column - 1; y > 0; y-- ) { // iterate from high to low

试试这个。

于 2012-06-28T15:57:41.350 回答