How to calculate the length of character array in C++
In this tutorial, we will see how to get the length of a char array in C++. A char array is just like we have an array of integers where we store the integer values in a contiguous memory location just like here we store char elements in a contiguous form. We can find the length of the char array by calculating each char element one by one or there are some built-in methods available with the help of them we can calculate the length of the char array as well. Let’s see all of them through examples one by one.
Example 1 – Using null character
#include<bits/stdc++.h> using namespace std; int main(){ char arr[] = "abcdefghi"; int count = 0; int i = 0; while(arr[i] != '\0'){ count++; i++; } cout<<"The length of a char array is: "<<count<<endl; return 0; }
Output –
The length of a char array is: 9
In this example, after assigning a char array in a while loop we compared each element with a null character. With the help of that null character, we can easily find out the length or size of any char array just like we did in the above code.
Example 2 – Traverse the array
#include<bits/stdc++.h> using namespace std; int main(){ char arr[] = "abcdefghi"; int count = 0; int i = 0; while(arr[i]){ count++; i++; } cout<<"The length of a char array is: "<<count<<endl; return 0; }
Output –
The length of a char array is: 9
Here first check the condition, The condition states that if there is an element present until then count the characters if there are no characters present stop the loop. According to that the while loop runs until there are characters as soon as the characters end the loop terminates and we will get the size of a character array.
Example 3 -Using sizeof operator
#include<bits/stdc++.h> using namespace std; int main(){ char arr[] = "abcdefghi"; int size = 0; size = sizeof(arr) - 1; cout<<"The length of a char array is: "<<size<<endl; return 0; }
Output –
The length of a char array is: 9
In this example, we use sizeof()
function to determine the length of the char array. Each character is of 1 byte so, after calculation size, we will get 10 but our size is 9 so why do we get 10? because it also added a null character so we have to subtract one null character from the total size to get the correct size of the char array. So these are some common examples to calculate the length of the char array. Hope this tutorial will be helpful.
Leave a Reply