Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Character array initialization and trailing null

Tags:

c++

When I declare a char array of size 2 and assign data to it when is there a trailing '\0' (null character)?

I know that:

char data[2] = {'a', 'b'}; // array holds 'a', 'b'

I also know that

char data[] = "ab"; // array holds 'a', 'b', '\0'

However, I'm wondering what this does?

char data[2] = "ab"; // Is there a trailing '\0'?

I always thought that this was an error however looking at cppreference it says:

If the size of the array is known, it may be one less than the size of the string literal, in which case the terminating null character is ignored:

char str[3] = "abc"; // str has type char[3] and holds 'a', 'b', 'c'

So what does "may" mean? Is it implementation dependent?

like image 586
LeviX Avatar asked Feb 01 '19 16:02

LeviX


People also ask

How do you initialize a char array with null?

You can't initialise a char array with NULL , arrays can never be NULL . You seem to be mixing up pointers and arrays. A pointer could be initialised with NULL . char str[5] = {0};

How do you initialize a character array?

In C++, when you initialize character arrays, a trailing '\0' (zero of type char) is appended to the string initializer. You cannot initialize a character array with more initializers than there are array elements. In ISO C, space for the trailing '\0' can be omitted in this type of information.

Does character array have null character?

the null character is used for the termination of array. it is at the end of the array and shows that the array is end at that point. the array automatically make last character as null character so that the compiler can easily understand that the array is ended.

Does char array end with null?

A C-style string is a null (denoted by \0 ) terminated char array. The null occurs after the last character of the string. For an initialization using double quotes, "...", the compiler will insert the null .


Video Answer


1 Answers

No, in C++ you must always make room for the NUL terminator:

char str[3] = "abc";

is required to issue a diagnostic.

In C, you can substitute "it is allowed to be" for may, and indeed

char str[3] = "abc";

is permitted, with the NUL terminator not being copied.

This is one of a number of important differences between C and C++.

like image 181
Bathsheba Avatar answered Nov 14 '22 12:11

Bathsheba