C: Dynamic arrays

2023-10-21

Dynamic array in C:

#include <stdio.h>
#include <stdlib.h>
int
main (void)
{
  //
  // Allocate with 5 elements
  //
  printf ("Allocating 5 elements ...\n");
  int *p = malloc (5 * sizeof (int));
  if (p == NULL)
    {
      printf ("Could not allocate.\n");
      return 1;
    }
  for (int i = 0; i < 5; ++i)
    {
      *(p + i) = i * 10;
    }
  for (int i = 0; i < 5; ++i)
    {
      printf ("p[%d] = %d\n", i, p[i]);
    }
  //
  // Reallocate with 10 elements
  //
  printf ("Reallocating 10 elements ...\n");
  p = realloc (p, 10 * sizeof (int));
  if (p == NULL)
    {
      printf ("Could not reallocate.\n");
      return 1;
    }
  for (int i = 0; i < 10; ++i)
    {
      *(p + i) = i * 100;
    }
  for (int i = 0; i < 10; ++i)
    {
      printf ("p[%d] = %d\n", i, p[i]);
    }
  //
  // Reallocate with 7 elements
  //
  printf ("Reallocating 7 elements ...\n");
  p = realloc (p, 7 * sizeof (int));
  if (p == NULL)
    {
      printf ("Could not reallocate.\n");
      return 1;
    }
  for (int i = 0; i < 7; ++i)
    {
      *(p + i) = i;
    }
  for (int i = 0; i < 7; ++i)
    {
      printf ("p[%d] = %d\n", i, p[i]);
    }
  //
  // Free
  //
  if (p != NULL)
    {
      free (p);
    }
  return 0;
}

Compiling

Compile with:

cc main.c

Executing

Execute program with:

./a.out

Output

Output:

Allocating 5 elements ...
p[0] = 0
p[1] = 10
p[2] = 20
p[3] = 30
p[4] = 40
Reallocating 10 elements ...
p[0] = 0
p[1] = 100
p[2] = 200
p[3] = 300
p[4] = 400
p[5] = 500
p[6] = 600
p[7] = 700
p[8] = 800
p[9] = 900
Reallocating 7 elements ...
p[0] = 0
p[1] = 1
p[2] = 2
p[3] = 3
p[4] = 4
p[5] = 5
p[6] = 6

← Home