0 votes
in C Plus Plus by
How do I find the length of an array in C/C++?

1 Answer

0 votes
by
How do I find the length of an array in C/C++?

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

Method 1 - Using sizeof operator

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.

Example

 Live Demo

#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;

Method 2 - Using pointers

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

Example

 Live Demo

#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;

}

Output

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;

Related questions

+2 votes
asked Jan 21, 2021 in C Plus Plus by SakshiSharma
+1 vote
asked Feb 6, 2020 in JavaScript by rajeshsharma
...