Arrays created using the []
syntax are not dynamic, the length is set at compile-time and cannot change.
UPDATE: Actually, C99 adds so-called "variable-length arrays", which can get their length at run-time. After they've been initialized, however, they can't shrink or expand so the below still applies.
However, an array is trivially expressed when you have pointers: an array can be represented as a pointer to the first element, and a length.
So, you can create a new array by dynamically allocating memory using malloc()
:
size_t array_length = 3;
int *array = malloc(array_length * sizeof *array);
if(array != NULL)
{
array[0] = 11;
array[1] = 22;
array[2] = 33;
}
You cannot use the {}
list of elements here, that's only usable when initializing arrays declared using the []
syntax.
To grow the array, you can use the realloc()
function to re-allocate the memory and copy the old values over:
size_t new_length = array_length + 1;
int *bigger_array = realloc(array, new_length * sizeof *bigger_array);
if(bigger_array != NULL)
{
bigger_array[new_length - 1] = 44;
/* We have successfully grown the allocation, remember the new address. */
array = bigger_array;
array_length = new_length;
}
Note that every time you call malloc()
(or realloc()
), it can return NULL
if it failed to allocate the requested block. That's why the if
statements are needed. I cut the initial size down a bit from your example to reduce the number of assignment-lines needed, to make the example shorter.
To make the above more efficient, typical dynamical array code uses two length values: one for the actual array (how many values are in the array right now) and one for the memory (how many values to we have room to store). By making the latter value grow in chunks, the total number of memory allocations can be cut down a bit, at the cost of some memory of course.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…