| Junio C Hamano | 3dac504 | 2007-12-15 08:40:54 | [diff] [blame] | 1 | allocation growing API |
| 2 | ====================== |
| 3 | |
| 4 | Dynamically growing an array using realloc() is error prone and boring. |
| 5 | |
| 6 | Define your array with: |
| 7 | |
| Junio C Hamano | c087f14 | 2013-01-10 23:38:50 | [diff] [blame] | 8 | * a pointer (`item`) that points at the array, initialized to `NULL` |
| 9 | (although please name the variable based on its contents, not on its |
| 10 | type); |
| Junio C Hamano | 3dac504 | 2007-12-15 08:40:54 | [diff] [blame] | 11 | |
| 12 | * an integer variable (`alloc`) that keeps track of how big the current |
| 13 | allocation is, initialized to `0`; |
| 14 | |
| 15 | * another integer variable (`nr`) to keep track of how many elements the |
| 16 | array currently has, initialized to `0`. |
| 17 | |
| Junio C Hamano | c087f14 | 2013-01-10 23:38:50 | [diff] [blame] | 18 | Then before adding `n`th element to the item, call `ALLOC_GROW(item, n, |
| Junio C Hamano | 3dac504 | 2007-12-15 08:40:54 | [diff] [blame] | 19 | alloc)`. This ensures that the array can hold at least `n` elements by |
| 20 | calling `realloc(3)` and adjusting `alloc` variable. |
| 21 | |
| 22 | ------------ |
| Junio C Hamano | c087f14 | 2013-01-10 23:38:50 | [diff] [blame] | 23 | sometype *item; |
| Junio C Hamano | 3dac504 | 2007-12-15 08:40:54 | [diff] [blame] | 24 | size_t nr; |
| 25 | size_t alloc |
| 26 | |
| 27 | for (i = 0; i < nr; i++) |
| Junio C Hamano | c087f14 | 2013-01-10 23:38:50 | [diff] [blame] | 28 | if (we like item[i] already) |
| Junio C Hamano | 3dac504 | 2007-12-15 08:40:54 | [diff] [blame] | 29 | return; |
| 30 | |
| 31 | /* we did not like any existing one, so add one */ |
| Junio C Hamano | c087f14 | 2013-01-10 23:38:50 | [diff] [blame] | 32 | ALLOC_GROW(item, nr + 1, alloc); |
| 33 | item[nr++] = value you like; |
| Junio C Hamano | 3dac504 | 2007-12-15 08:40:54 | [diff] [blame] | 34 | ------------ |
| 35 | |
| 36 | You are responsible for updating the `nr` variable. |