![]() |
VOOZH | about |
The Length of an array in C refers to the maximum number of elements that an array can hold.
5
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
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.
5
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.