]>
Commit | Line | Data |
---|---|---|
530e741c JH |
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 | ||
5062f9e1 AS |
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); | |
530e741c JH |
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 | ||
5062f9e1 | 18 | Then before adding `n`th element to the item, call `ALLOC_GROW(item, n, |
530e741c JH |
19 | alloc)`. This ensures that the array can hold at least `n` elements by |
20 | calling `realloc(3)` and adjusting `alloc` variable. | |
21 | ||
22 | ------------ | |
5062f9e1 | 23 | sometype *item; |
530e741c JH |
24 | size_t nr; |
25 | size_t alloc | |
26 | ||
27 | for (i = 0; i < nr; i++) | |
5062f9e1 | 28 | if (we like item[i] already) |
530e741c JH |
29 | return; |
30 | ||
31 | /* we did not like any existing one, so add one */ | |
5062f9e1 AS |
32 | ALLOC_GROW(item, nr + 1, alloc); |
33 | item[nr++] = value you like; | |
530e741c JH |
34 | ------------ |
35 | ||
36 | You are responsible for updating the `nr` variable. | |
3ac22f82 RS |
37 | |
38 | If you need to specify the number of elements to allocate explicitly | |
39 | then use the macro `REALLOC_ARRAY(item, alloc)` instead of `ALLOC_GROW`. |