How to initialize a Char Array in C++?

This tutorial will discuss about a unique way to initialize a char array in C++.

We can initialze a char array with a string while defining the array. Like this,

char arr[50] = "Sample text";

But we need to make sure that the array is big enough to hold all the characters of string. Otherwise you will get compile error. For example, if we try to initialze a char array of size 3, with a string that has more characters than that, then it will raise an error. For example,

char arr[3] = "abc";

Error:

error: initializer-string for array of chars is too long [-fpermissive]
   5 |     char arr[3] = "abc";

Also, all the strings in C++ are terminated by a null character. So, to hold a string like this –> “abc”, we need a char array of size 4, because the last character is the null character i.e. ‘\0’.

Although we can also initialize a char array, just like any other array instead of a null terminated string i.e.

char arr2[3] = {'a', 'b', 'c'};

This char array has different characters in it, but we can not use it as a string because there is no null character in this char array. If we try to print this array, then it will cause an undefined behaviour.

Let’s see the complete example,

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

int main()
{

    // Initialize a char array with string
    char arr[10] = "sample";

    std::cout<< arr << std::endl;

    // Initialize a char array manually
    char arr2[3] = {'a', 'b', 'c'};

    // Print each character of char array in separate line
    for(int i = 0; i < sizeof(arr2) / sizeof(arr2[0]); i++)
    {
        std::cout<< arr2[i] << std::endl;
    }

    // Will print garbage
    std::cout<<arr2<<std::endl;

    return 0;

}

Output :

sample
a
b
c
abcsample

Summary

Today we learned about several ways to how to initialize a 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