Find size of an array in C using sizeof operator and pointer arithmetic

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


1. sizeof operator

The standard way is to use sizeof operator to find size of an C-style array. The sizeof operator on an array returns the total memory occupied by the array in bytes. To determine the number of elements in the array, 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 readibility, it is suggested to construct a MACRO out of it as shown below:


Download   Run Code

We know that 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 size of the array arr. 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

Read More: Find length of an array in C++

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂


Leave a Reply

Notify of