Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does std::array initializer work for char's?

I'm not sure how the following code works. I thought you had to do {'h', 'e' ...etc...} but it seems to work fine. On the other hand if you do std::array<const char* it only adds one element to the array. Are there special rules for string literal initialization?

std::array<char, strlen("hello world!") + 1> s = {"hello world!"};
for (size_t i = 0; i < s.size(); ++i)
{
    std::cout << s[i];
}
like image 663
user4051846 Avatar asked Sep 17 '14 19:09

user4051846


1 Answers

Class std::array is an aggregate. In this statement:

std::array<char, strlen("hello world!") + 1> s = {"hello world!"};

list initialization is used. As the first and only element of this instantiation of the class std::array is a character array it may be initialized with string literals.

It would be more correctly to use sizeof operator instead of function strlen:

std::array<char, sizeof( "hello world!" )> s = {"hello world!"};

Also you could write

std::array<char, sizeof( "hello world!" )> s = { { "hello world!" } };

because the character array in turn is an aggregate.

According to the C++ Standard

8.5.2 Character arrays [dcl.init.string]

1 An array of narrow character type (3.9.1), char16_t array, char32_t array, or wchar_t array can be initialized by a narrow string literal, char16_t string literal, char32_t string literal, or wide string literal, respectively, or by an appropriately-typed string literal enclosed in braces (2.14.5). Successive characters of the value of the string literal initialize the elements of the array.

[ Example:

char msg[] = "Syntax error on line %s\n";
like image 114
Vlad from Moscow Avatar answered Oct 15 '22 06:10

Vlad from Moscow