How to determine the length of an array using sizeof in C language?

In C language, the sizeof operator can be used to determine the length of an array.

Assume there is an integer array arr, you can find its length using the following method:

int arr[] = {1, 2, 3, 4, 5};
int length = sizeof(arr) / sizeof(arr[0]);

In the code above, sizeof(arr) represents the total size of the array and sizeof(arr[0]) represents the size of each element in the array. Dividing the total size by the size of each element gives the length of the array.

It should be noted that this method only applies to cases where the array has already been defined. If only the pointer to the array is available without the array itself being defined, then the length of the array cannot be determined using the sizeof operator.

bannerAds