Get the length of char array in C++

This tutorial will discuss about a unique way to get the length of char array in C++.

Get maximum number of elements an array can hold

We can get the length of a char array, just like an another array i.e. fetch the actual size of array using sizeof(arr), and divide it with the size of first element in array i.e. sizeof(arr[0]). It will give us the size of array i.e. the number of maximum characters that this array can hold. For example,

char arr[10] = "sample";

// Get length of a char array
size_t len = sizeof(arr) / sizeof(arr[0]);

std::cout<< len << std::endl;

Output:

10

As the string in this char array contains only 5 characters. But as the char array can hold 10 characters, therefore it returned the value 10.

Get the number of characters in a char array (string)

We can use the strlen() function from string.h header file. It accepts a char array as an argument, and treats the value in char array as a null terminated string. It returns the number of character in string holded by the char array. It excludes the null character at the end of string.

char arr[10] = "sample";

// Get number of characters in a char array
size_t count = strlen(arr);

std::cout<< count << std::endl;

Output:

6

As there were only six characters in the string, therefore it returned the value 6.

Let’s see the complete example,

#include <iostream>
#include <string.h>

using namespace std;

int main()
{

    char arr[10] = "sample";

    // Get length of a char array
    size_t len = sizeof(arr) / sizeof(arr[0]);

    std::cout<< len << std::endl;

    // Get number of characters in a char array
    size_t count = strlen(arr);

    std::cout<< count << std::endl;

    return 0;
}

Output :

10
6

Summary

Today we learned about several ways to get the length of char array in C++. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top