5 Ways to find length of an array in c++ including character array
5 WAYS to find Length of an ARRAY data-type in C++- Using sizeof( ) function
- Counting element - by- element also known as Traversing
a)Char array b) other data type arrays like int,float - Using size ( ) function in STL
- Using begin ( ) and end ( )
- Using Pointers
a)Char array b) other data type arrays like int,float
1. Using Sizeof( ) operator:
In C++, the
sizeof operator is used to determine the size of a variable or data type in bytes. The operator can be used with variables, arrays, or data types.When used with a variable, sizeof returns the number of bytes occupied by the variable in memory. We will discuss this keeping arrays in our mind only.
Example of using sizeof( ) to find the array length.
* same technique can be used on character arrays
Output:
2.1 Counting elements by traversing the array
2.2 Other way of traversing whole array.
Output:
3. Using size( ) function in STL
Alternatively, We can use
std::array instead of a raw array, which has the size() function. We can not use RAW array and must include header file #include<array>
4. Using begin( ) and end( ) :
In C++, we can use the begin() and end() member functions of the std::array class to determine the length of an array.
For a std::array, the begin() member function returns an iterator pointing to the first element of the array, and the end() member function returns an iterator pointing one past the last element of the array. To determine the length of the array, you can subtract the value of begin() from end() as shown in the following example:
Note: Instead of distance function , you can simply subtract the end from the beginning.
Also the same can be done on the RAW arrays.
5. Using Pointers:
Please note that although this code may work in practice for statically allocated arrays, it is not guaranteed to work in all cases. The behavior is implementation-dependent, and it may not produce the correct result for dynamically allocated arrays or arrays passed as function arguments.-end of blog -

Comments
Post a Comment