Je suis sûr que vous (les pros) pouvez identifier le bug 'dans mon code, j'apprécierais également tous les autres commentaires sur mon code.Bogue d'allocation de mémoire dynamique simple
BTW, le code se bloque après l'avoir exécuté.
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
typedef struct
{
int x;
int y;
} Location;
typedef struct
{
bool walkable;
unsigned char walked; // number of times walked upon
} Cell;
typedef struct
{
char name[40]; // Name of maze
Cell **grid; // 2D array of cells
int rows; // Number of rows
int cols; // Number of columns
Location entrance;
} Maze;
Maze *maz_new()
{
int i = 0;
Maze *mazPtr = (Maze *)malloc(sizeof (Maze));
if(!mazPtr)
{
puts("The memory couldn't be initilised, Press ENTER to exit");
getchar();
exit(-1);
}
else
{
// allocating memory for the grid
mazPtr->grid = (Cell **) malloc((sizeof (Cell)) * (mazPtr->rows));
for(i = 0; i < mazPtr->rows; i++)
mazPtr->grid[i] = (Cell *) malloc((sizeof (Cell)) * (mazPtr->cols));
}
return mazPtr;
}
void maz_delete(Maze *maz)
{
int i = 0;
if (maz != NULL)
{
for(i = 0; i < maz->rows; i++)
free(maz->grid[i]);
free(maz->grid);
}
}
int main()
{
Maze *ptr = maz_new();
maz_delete(ptr);
getchar();
return 0;
}
Merci d'avance.
Pourquoi consacrez-vous pas la grille aller? par exemple. maxPtr-> grille = malloc (sizeof (Cell) * mazPtr-> lignes * mazPtr-> cols); Je trouve que l'accès aux cellules comme celui-ci est conceptuellement plus simple. –