- Related Questions & Answers
- How do you find the length of an array in C#?
- How do you find the number of dimensions of an array in C#?
- How to find the length of an array in JavaScript?
- How do I determine the size of my array in C#
- Find the Derangement of An Array in C++
- How to find the length and rank of a jagged array in C#?
- How to find the length of the StringBuilder in C#?
- Find the length of each string element in the Numpy array in C++
- How do I empty an array in JavaScript?
- Where do I find the current C or C++ standard documents?
- How do you empty an array in C#?
- How do I get the average string length in MySQL?
- How do I overload the [] operator in C#?
- How do I use the conditional operator in C/C++?
- How do I sort a two-dimensional array in C#

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Some of the methods to find the length of an array are given as follows −

The sizeof() operator can be used to find the length of an array. A program that demonstrates the use of the sizeof operator in C++ is given as follows.

#include <iostream> using namespace std; int main() { int arr[5] = {4, 1, 8, 2, 9}; int len = sizeof(arr)/sizeof(arr[0]); cout << "The length of the array is: " << len; return 0; }

The output of the above program is as follows −

The length of the array is: 5

Now, let us understand the above program.

The variable len stores the length of the array. The length is calculated by finding size of array using sizeof and then dividing it by size of one element of the array. Then the value of len is displayed. The code snippet for this is given as follows −

int arr[5] = {4, 1, 8, 2, 9}; int len = sizeof(arr)/sizeof(arr[0]); cout << "The length of the array is: " << len;

Pointer arithmetic can be used to find the length of an array. A program that demonstrates this is given as follows.

#include <iostream> using namespace std; int main() { int arr[5] = {5, 8, 1, 3, 6}; int len = *(&arr + 1) - arr; cout << "The length of the array is: " << len; return 0; }

The output of the above program is as follows −

The length of the array is: 5

Now, let us understand the above program.

The value contained in *(&arr + 1) is the address after 5 elements in the array. The value contained in arr is the address of the starting element in array. So their subtraction results in the length of the array. The code snippet for this is given as follows −

int arr[5] = {5, 8, 1, 3, 6}; int len = *(&arr + 1) - arr; cout << "The length of the array is: " << len;

Advertisements