Length of Array in C (original) (raw)

Last Updated : 17 Jan, 2025

The Length of an array in C refers to the maximum number of elements that an array can hold. It must be specified at the time of declaration. It is also known as the size of an array that is used to determine the memory required to store all of its elements.

In C language, we don't have any pre-defined function to find the length of the array instead, you must calculate the length manually using techniques based on how the array is declared and used.

The simplest method to find the length of an array is by using **sizeof() operator to get the total size of the array and then divide it by the size of one element.Take a look at the below example:

C `

#include <stdio.h>

int main() { int arr[5] = { 1, 2, 3, 4, 5 };

// Find the size of the array arr
int n = sizeof(arr) / sizeof(arr[0]);

printf("%d", n);
return 0;

}

`

**Explanation: In this program, the total size of the array **arr (20 bytes) is divided by the size of a single element in the array (4 bytes). This gives the number of elements in the array, which is **20/4 = 5

Using Pointer Arithmetic Trick

We can also calculate the length of an array in C using **pointer arithmetic. This solution of using a pointer is just a hack that is used to find the number of elements in an array.

C `

#include <stdio.h> int main(){

int arr[5] = { 1, 2, 3, 4, 5 };

// Find the size of array arr
int n = *(&arr + 1) - arr;

printf( "%d", n);
return 0;

}

`

**Explanation: In the above code, in the expression: ***(&arr + 1) - arr; is the main logic. Here is how it works,

**Note: Please note that these methods only works when the array is declared in the same scope. These methods will fail if we try them on an array which is passed as a pointer. This happens due to Array Decay. So, it is recommended to keep a variable that tracks the size of the array.

For more insights into array handling and other key data structures in C, our **C programming course offers comprehensive lessons on arrays, pointers, and memory management.