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

CC++Server Side Programming

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;
raja
Published on 21-Nov-2018 16:18:41
Advertisements