This post provides an overview of some of the available alternatives to find the size of an array in C.

1. sizeof operator

The standard way is to use the sizeof operator to find the size of a C-style array. The sizeof operator on an array returns the total memory occupied by the array in bytes. To determine the total number of the array elements, the trick is to divide the total memory occupied by the array by the size of each element. This is demonstrated below in C:

Download  Run Code

 
For simplicity and to improve code readability, it is suggested to construct a MACRO out of it, as shown below:

Download  Run Code

 
We know that an array decays into a pointer when passed to a function as an argument regardless of whether the parameter is declared as int[] or not. So, above approach works only with the static arrays but fails on the dynamically allocated arrays and function parameters as they both involve pointers.

Download  Run Code

2. Using pointer arithmetic

The trick is to use the expression (&arr)[1] - arr to get the array arr size. Both arr and &arr points to the same memory location, but they both have different types.

  1. arr has the type int* and decays into a pointer to the first element of the array. Hence, any knowledge about the size of the array is gone.
  2. &arr results in a pointer of type int (*)[n], i.e., a pointer to an array of n ints. So, &arr points to the entire array and *(&arr + 1) (or &arr)[1]) points to the next byte after the array.

This works because of the way pointer arithmetic works in C. We know that a pointer to int is advanced by sizeof(int) when incrementing by 1. Similarly, a pointer to int[n] is advanced by sizeof(int[n]), which is the size of the entire array.

Download  Run Code

That’s all about finding the size of an array in C using sizeof operator and pointer arithmetic.

 
Read More:

Find the length of an array in C++