0

这是我的问题:我有一个二维字符矩阵,我用一个函数进行了 malloc。之后,我想从文件中获取地图,但我有一个分段错误,我不知道为什么......这是一个代码示例:

// struct where I put the map and others informations from the  
typedef struct problem_t
{
    char *nom;
    Coordonnees arrivee, depart;
    int nb_ligne, nb_col;
    char **     
} Problem;

// Function wich malloc the map
int mallocCarte( char *** carte, int nbLigne, int nbCol )
{
    *carte = malloc( nbLigne * sizeof( char* ) );

    if ( *carte == NULL )
    {
        return false;
    }

    int i;
    for ( i = 0; i < nbLigne ; ++i )
    {

        (*carte) [i] = malloc( nbCol * sizeof( char ) );
        if ( (*carte) [i] == NULL )
        {
            return false;
        }
    }

    return true;

} // mallocCarte  ()

// Code sample, I've already got the others informations, now, I'd like to get the map
// On commence par reserver l'espace memoire reserve à la carte.
int res = mallocCarte( &problem->carte, problem->nb_ligne, problem->nb_col );

// Si l'allocation s'est mal passée, on renvoie un message
if ( res == false )
{
    exc.num_Exc = MALLOC_ERROR;
    exc.msg_Err = "Erreur lors de l'allocation mémoire de la carte";
    return exc;
}

printf( "Recuperation de la carte 2 ...%d %d\n", problem->nb_ligne,
        problem->nb_col );
int nbLi = 0;
int nbCol = 0;
while ( fgets( fromFile, 1, file ) != NULL && nbLi < problem->nb_ligne )
{
    if ( fromFile [0] == '\n' )
    {
        nbCol = 0;
        ++nbLi;
        continue;
    }

    if ( nbCol == problem->nb_col )
    {
        printf( "malformed input file!\n" );
        exit( -1 );
    }


    ( problem->carte ) [nbLi] [nbCol++] = fromFile [0];
}

已经很多天了,我真的不知道该怎么办......如果有人可以帮助我,我会非常感激!

谢谢

(这是我获取信息的源文件。首先是问题名称,然后是一些坐标,最后是地图大小。文件末尾是地图 https://dl.dropbox.com/u/56951442/地图.txt )

4

2 回答 2

1

当您增加nbLimain,您需要重置nbCol为零。您允许列继续无限增加并超过数组的大小。

此外,您不应该malloc在 C 中强制转换

此外,您应该将 &problem->carte 传递给您的分配函数...

// Function wich malloc the map
int mallocCarte( char *** carte, int nbLigne, int nbCol )
{
    *carte = malloc( nbLigne * sizeof( char* ) );
...
    (*carte)[i] = malloc( nbCol * sizeof( char ) );
...
}

main()
{
   ...
   int res = mallocCarte( &problem->carte, problem->nb_ligne, problem->nb_col );
   ...
}

您可能还应该添加一个测试,以确保如果您的输入文件格式不正确,您不会离开列的末尾......

   if ( isspace( fromFile [0] ) )
   {
       nbCol = 0;
       ++nbLi;
       continue;
   }

   if( nbCol == problem->nb_col )
   {
       printf( "malformed input file!\n" );
       exit( -1 );
   }

你确定你的意思是使用fgets( fromFile, 1, file )?下面的描述意味着在文件结束之前总是fgets()返回一个空字符串,并且一直是until 。你应该使用fromFile[0]'\0'EOFfgets( fromFile, 2, file )

fgets() 从流中最多读入一个小于 size 的字符,并将它们存储到 s 指向的缓冲区中。在 EOF 或换行符后停止读取。如果读取了换行符,则将其存储到缓冲区中。'\0' 存储在缓冲区中的最后一个字符之后。

于 2013-04-09T17:12:50.873 回答
-1

问题是结构问题_t 的对象。它不是指针,您应该访问结构变量,例如

problem.carte,
problem.nb_ligne
problem.nb_col

我在我的系统上尝试了你的代码。使用给定的 map.txt,您的代码对我来说运行良好。我刚刚声明了 char fromFile[2]; While(fgets(fromFile,2,file) != NULL) {//打印文件}。它的打印文件适合我。

于 2013-04-09T17:40:44.110 回答