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?
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};
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.
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.
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 .
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++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With