The C-language has several types of arrays. We shall mostly use one-dimensional arrays and a little bit of arrays-of-arrays.
A one-dimensional array can store several values—called
array elements—of the same type. Useful for vectors
and matrices. The element number i
of the double array
a
can be accessed as a[i]
,
a[0]=1.23; print("element number 0 equals %g\n",a[0]);The numbering of elements in a C-arrays starts with zero.
The arrays in C—generally speaking—do not know their sizes (compiler might figure out sometimes but you shouldn't rely on this). The sizes must be passed around together with the arrays.
An array where the number of elements is known at compile-time, say 9, can be declared as
double a[9];The numbering of elements starts with 0, hence the array elements are from
a[0]
to a[8]
.
After this declaration the compiler reserves (allocates) a block of memory in the stack to keep 9 double values. The array is kept in memory until it gets out of scope when it is automatically deallocated.
In the C99 standard the arrays can also be declared at run-time. They are called Variable Length Arrays (VLA)
double a[n];VLAs are also allocated in the stack and are also automatically deallocated when out of scope.
The stack can only keep relatively small arrays. Large arrays must be
allocated in the heap using the malloc
function
double* a = malloc(n*sizeof(double));
The arrays allocated using malloc
must be manually
deallocated using the free
function,
free(a);It is your responsibility to free memory allocated by
malloc
. There must be a free
for every
malloc
. Forgetting to free memory might lead to memory-leaks.