Created
January 10, 2018 17:49
-
-
Save clausecker/125cde1f20583ca5f2e8bface7088b42 to your computer and use it in GitHub Desktop.
Fibonacci growth example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| static struct puzzle * | |
| read_puzzles(size_t *n_puzzle, FILE *puzzlefile) | |
| { | |
| struct puzzle *puzzles; | |
| size_t cap = 64, n_linebuf; | |
| char *linebuf = NULL; | |
| *n_puzzle = 0; | |
| puzzles = malloc(cap * sizeof *puzzles); | |
| if (puzzles == NULL) { | |
| perror("malloc"); | |
| exit(EXIT_FAILURE); | |
| } | |
| while (getline(&linebuf, &n_linebuf, puzzlefile) != -1) { | |
| if (*n_puzzle >= cap) { | |
| /* Fibonacci growth */ | |
| cap = cap * 13 / 8; | |
| assert(cap > *n_puzzle); | |
| puzzles = realloc(puzzles, cap * sizeof *puzzles); | |
| if (puzzles == NULL) { | |
| perror("realloc"); | |
| exit(EXIT_FAILURE); | |
| } | |
| } | |
| if (puzzle_parse(puzzles + (*n_puzzle)++, linebuf) != 0) { | |
| fprintf(stderr, "Invalid puzzle: %s", linebuf); | |
| exit(EXIT_FAILURE); | |
| } | |
| assert(puzzle_valid(puzzles + *n_puzzle - 1)); | |
| } | |
| if (ferror(puzzlefile)) { | |
| perror("getline"); | |
| exit(EXIT_FAILURE); | |
| } | |
| free(linebuf); | |
| return (puzzles); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment