Tilbage til slide -- Tastaturgenvej: 'u'  forrige -- Tastaturgenvej: 'p'  næste -- Tastaturgenvej: 'n'          arrays/dynamic-array-1.c - Et program der foretager dynamisk allokering af et array - malloc.Lektion 9 - slide 27 : 30
Program 4

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

int main(void){
  int *a, i, n, sum = 0;

  /* Prompt for size of array: */
  printf("Enter an integer size:\n");
  scanf("%d",&n);
   
  /* Allocate space for n * sizeof(int) bytes. Dynamic allocation.
     Returns a generic pointer to the allocated meory.
     NOT initialized to 0.  */
  a = (int *)malloc(n * sizeof(int));  
                                   
  if (a == NULL){
     printf("Cannot allocate enough memory. Bye");
     exit(EXIT_FAILURE);
  }

  /* Initialize the array somehow: */
  for (i = 0; i < n; i++)
     a[i] = 2*i;

  /* Sum up the elements: */
  for (i = 0; i < n; i++)
      sum += a[i];

  free(a);                      /* FREE THE SPACE */

  printf("Sum of %d elements: %d\n", n, sum);

  return 0;
}