Dynamic allocation of arrays

Content

Arrays can be declared local to a function or at a global level:

double x[8]; /* declared at a global level */

void f() {
   double y[8]; /* declared local to function f */
   /* ... */
}

Global variables like x exist in one instance only during the whole runtime of the process. Local variables, like y within f, are instantiated for each invocation of f and the instantiation ceases to exist when the invocation is ended by an explicit return-statement or reaching the end of the function.

The size of a global array must be known at compile-time. Local arrays can have a dynamic size (beginning with C99) but care must be taken as stack space is usually very limited.

Additionally, we can also allocate an array (or any kind of data structure) on the heap with a dynamic size. This can be done using the standard function malloc (#include <stdlib.h> is required) which expects the number of bytes to be allocated and returns a pointer to it of type void* which is some sort of wildcard-pointer that can be easily converted to any other pointer type. Example:

#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>

void init_vector(double* v, size_t len, ptrdiff_t incr) {
   for (size_t i = 0; i < len; ++i) {
      v[i*incr] = i + 1;
   }
}

double sum(double* x, size_t len, ptrdiff_t incr) {
   double result = 0;
   for (size_t i = 0; i < len; ++i) {
      result += x[i * incr];
   }
   return result;
}

int main() {
   printf("vector length = ");
   size_t len;
   if (scanf("%zu", &len) != 1) return 1;
   double* vector = (double*) malloc(sizeof(double) * len);
   if (!vector) {
      printf("unable to allocate heap memory for %zd double values\n",
	 len);
      return 1;
   }
   init_vector(vector, len, 1);
   printf("sum = %lg\n", sum(vector, len, 1));
   free(vector);
}

Some notes:

Exercise

Rewrite your solution to the first task to allow for a dynamic array length which is read from standard input.