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]
,
the numbering of elements in a C-array starts with zero,
double a[7]; /* allocates memory in the stack for 7 double numbers a[0], a[1], ..., a[6] */ a[0]=1.23; print("element number 0 equals %g\n",a[0]);
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.
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.
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.