diff options
| author | Kirill Petrashin <kirill8201@yandex.ru> | 2026-03-29 14:52:47 +0300 |
|---|---|---|
| committer | Kirill Petrashin <kirill8201@yandex.ru> | 2026-03-29 14:52:47 +0300 |
| commit | 5e7591a2f684bba637e120497a2ba0fdd3db8dda (patch) | |
| tree | 344e55bf37a8bae5a31f231108a20bd57a3f4cb8 | |
| parent | 7a69d0103dadc08f228d14b27d38df193044bb29 (diff) | |
| download | astar-5e7591a2f684bba637e120497a2ba0fdd3db8dda.tar.xz | |
Make the stack dynamic
| -rw-r--r-- | map.c | 1 | ||||
| -rw-r--r-- | stack.c | 10 | ||||
| -rw-r--r-- | stack.h | 12 |
3 files changed, 16 insertions, 7 deletions
@@ -158,6 +158,7 @@ Map rbt_maze_map(size_t width, size_t height, unsigned int seed) { } while (ps_peek(ps).x != beginning_cell.x || ps_peek(ps).y != beginning_cell.y) ; visited_free(visited, height); + ps_free(ps); return map; } @@ -6,12 +6,17 @@ PositionStack ps_new(void) { PositionStack ps; + ps.capacity = STACK_INITIAL_CAPACITY; + ps.arr = malloc(sizeof(Position) * ps.capacity); ps.top = 0; return ps; } int ps_push(PositionStack *ps, Position pos) { - if (ps->top >= STACK_SIZE) return -1; /* FIXME: do a dynamic stack */ + if (ps->top >= ps->capacity) { + ps->capacity *= STACK_SIZE_COEFFICIENT; + if ((ps->arr = realloc(ps->arr, sizeof(Position) * ps->capacity)) == NULL) return -1; + } ps->arr[ps->top] = pos; ps->top += 1; return 0; @@ -28,3 +33,6 @@ Position ps_peek(PositionStack ps) { return ps.arr[ps.top - 1]; } +void ps_free(PositionStack ps) { + free(ps.arr); +} @@ -4,20 +4,20 @@ #include <stddef.h> #include "structs.h" -/* So, the implementation of the stack is array-based, for hyperspeed. - * For bigger maps we have to increase the STACK_SIZE, but it should - * work fine most of the time. I guess */ -#define STACK_SIZE 4096 +#define STACK_INITIAL_CAPACITY 4096 +#define STACK_SIZE_COEFFICIENT 2 struct PositionStack_s { - Position arr[STACK_SIZE]; /* The array with all the values */ + Position *arr; /* The array with all the values */ + size_t capacity; size_t top; /* Shows where the top of the stack is */ }; typedef struct PositionStack_s PositionStack; PositionStack ps_new(void); /* Returns an empty position stack */ -int ps_push(PositionStack *ps, Position pos); /* Returns -1 if overflow */ +int ps_push(PositionStack *ps, Position pos); /* Returns -1 if failed to realloc() */ Position ps_pop(PositionStack *ps); Position ps_peek(PositionStack ps); +void ps_free(PositionStack ps); #endif /* STACK_H_ */ |
