blob: 542946b1ba701069837b702cbd8fe8079cecf56d [file] [log] [blame]
Junio C Hamano3dac5042007-12-15 08:40:541allocation growing API
2======================
3
4Dynamically growing an array using realloc() is error prone and boring.
5
6Define your array with:
7
Junio C Hamanoc087f142013-01-10 23:38:508* 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 Hamano3dac5042007-12-15 08:40:5411
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 Hamanoc087f142013-01-10 23:38:5018Then before adding `n`th element to the item, call `ALLOC_GROW(item, n,
Junio C Hamano3dac5042007-12-15 08:40:5419alloc)`. This ensures that the array can hold at least `n` elements by
20calling `realloc(3)` and adjusting `alloc` variable.
21
22------------
Junio C Hamanoc087f142013-01-10 23:38:5023sometype *item;
Junio C Hamano3dac5042007-12-15 08:40:5424size_t nr;
25size_t alloc
26
27for (i = 0; i < nr; i++)
Junio C Hamanoc087f142013-01-10 23:38:5028if (we like item[i] already)
Junio C Hamano3dac5042007-12-15 08:40:5429return;
30
31/* we did not like any existing one, so add one */
Junio C Hamanoc087f142013-01-10 23:38:5032ALLOC_GROW(item, nr + 1, alloc);
33item[nr++] = value you like;
Junio C Hamano3dac5042007-12-15 08:40:5434------------
35
36You are responsible for updating the `nr` variable.