]> rtime.felk.cvut.cz Git - git.git/blob - Documentation/technical/api-allocation-growing.txt
Update draft release notes to 1.7.2
[git.git] / Documentation / technical / api-allocation-growing.txt
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
8 * a pointer (`ary`) that points at the array, initialized to `NULL`;
9
10 * an integer variable (`alloc`) that keeps track of how big the current
11   allocation is, initialized to `0`;
12
13 * another integer variable (`nr`) to keep track of how many elements the
14   array currently has, initialized to `0`.
15
16 Then before adding `n`th element to the array, call `ALLOC_GROW(ary, n,
17 alloc)`.  This ensures that the array can hold at least `n` elements by
18 calling `realloc(3)` and adjusting `alloc` variable.
19
20 ------------
21 sometype *ary;
22 size_t nr;
23 size_t alloc
24
25 for (i = 0; i < nr; i++)
26         if (we like ary[i] already)
27                 return;
28
29 /* we did not like any existing one, so add one */
30 ALLOC_GROW(ary, nr + 1, alloc);
31 ary[nr++] = value you like;
32 ------------
33
34 You are responsible for updating the `nr` variable.