7

How to initialize a Char Array in C++?

 1 year ago
source link: https://thispointer.com/how-to-initialize-a-char-array-in-c/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to initialize a Char Array in C++? – thisPointer

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";
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";
char arr[3] = "abc";

Error:

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

Advertisements

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'};
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;
#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
abcsample
sample
a
b
c
abcsample

Summary

Today we learned about several ways to how to initialize a char array in C++?. Thanks.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK