這裏是我的問題:我有一個二維矩陣焦炭至極我用的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