Skip to content
Physics and Astronomy
Home Our Teaching Resources C programming Example
Back to top

Dynamic memory allocation example

The example of two-dimensional dynamic allocation in the lecture did everything inside of main(). But the process of allocating and freeing these arrays had more than one step and these steps had to be done in the right order. This makes them classic candidates for a function. We demonstrate a suitable code here, and for variety use ints rather than floats

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

// Allocate a 2-D array of ints
int **new2dint(int m, int n) {
  int **p;
  int i;

  p = xmalloc(m * sizeof *p);
  for (i = 0; i < m; ++i)
    p[i] = malloc(n * sizeof *p[i]);
  return p;
}

// Free a 2-D array of ints
void free2dint(int **p, int m) {
  for (int i = 0; i < m; ++i)
    free(p[i]);
  free(p);
}

int main() {
  int **p = NULL;
  int m, n;

  do {
    printf("Sizes of array (>0)?\n");
    scanf("%i %i", &m, &n);
  } while (n <= 0 || m <= 0);

  p = new2dint(m, n);
  p[0][1] = 17;
  p[m-1][0] = 13;
  p[m-1][n-1] = 10;

  free2dint(p, m); // To demonstrate

  return 0;
}
Step through this code


Note that we do not actually need call free() in this case as the program is finishing anyway, but we do as a demonstration.

                                                                                                                                                                                                                                                                       

Validate   Link-check © Copyright & disclaimer Privacy & cookies Share
Back to top