这里是我的问题:我有一个二维矩阵焦炭至极我用的malloc函数。后来,我想从一个文件中的地图,但是我有一个分段错误在那里,我不知道为什么... 下面是一个代码示例:ç - 的malloc或与fgets,我不知道发生了什么不工作
// 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/map.txt)
这是否甚至编译?..我有一些关于'struct'声明的char **'行的疑问。 – dasblinkenlight 2013-04-09 17:08:32
您不需要在C程序中投射'malloc'的返回值。 'sizeof(char)'是'1'。 – 2013-04-09 17:09:13
如果你想通过out参数返回一个2d数组,参数需要'char ***'类型。然后你的第一个任务就像'carte = malloc(nbLigne * sizeof(char *));' – jpm 2013-04-09 17:11:45