C: Get number of elements of an array

2023-10-21

Get the number of elements of an array:

#include <stdio.h>
int
main (void)
{
  int a[] = { 10, 20, 30 };
  size_t numelements = sizeof (a) / sizeof (a[0]);
  printf ("array has %ld elements.\n", numelements);
  for (int i = 0; i < numelements; ++i)
    {
      printf ("a[%d] = %d\n", i, a[i]);
    }
  return 0;
}

Compiling

Compile with:

cc main.c

Executing

Execute program with:

./a.out

Output

Output:

array has 3 elements.
a[0] = 10
a[1] = 20
a[2] = 30

← Home