You are browsing as a guest. Sign up (or log in) to start making projects!

46m 16s logged

C Navigation System — Devlog #4: Dynamic Map

The feedback from the certification reviewer included a clear suggestion for the next step: make the map dynamic, and possibly allow variable dimensions instead of keeping it fixed at 10×10. That’s what I focused on in this stage.

The first challenge was realizing that a normal C array, such as char lab[10][10], isn’t suitable for this. The size of a regular array has to be known at compile time, but in this case the dimensions are only known after the user enters them at runtime. The solution was to use dynamic memory allocation with malloc.

For a dynamic 2D map, this is done in two steps: first, allocate an array of pointers (one for each row), then allocate each row individually.

char **lab = malloc(rows * sizeof(char *));
for (int i = 0; i < rows; i++) {
    lab[i] = malloc(columns * sizeof(char));
}

The eh_obstaculo function, which previously had the entire maze hardcoded inside it, became much simpler. It now just receives the map as a parameter (char **lab) and checks the requested position.

int eh_obstaculo(int x, int y, char **lab) {
    return lab[x][y] == '#';
}

To populate the map, I use fgets to read each row entered by the user, rather than asking for one position at a time, which would have been much more tedious to use.

The part that took the most work wasn’t the map itself, but realizing that every other data structure used by the BFS (visited, parent, and queue) also depended on the old fixed TAM value. They all had to be converted to dynamically allocated structures based on the number of rows and columns. The parent array, for example, became an int *** because each cell stores a pair of coordinates (x, y) representing its parent, which adds another level of indirection.

In the end, the program asks the user for the number of rows and columns, reads the map line by line, runs the BFS using these dynamic structures, and finally frees all allocated memory with free, including the parent array, which has to be released from the innermost allocations outward because of its three levels of allocation.

The biggest lesson from this stage was realizing that making the map “dynamic” isn’t just about changing one variable. It means redesigning the entire chain of data structures that depended on the original fixed-size implementation.

0
7

Comments 0

No comments yet. Be the first!