Michael wrote:
How to understand the difference between the following three.
My understanding is the number in bracket minus one is the max number
of chars to store in the char array , right?
The confusion is apparently between "an array of char" and "a C string".
The former just stores those chars. The latter stores chars _and_ is
terminated with a char with the value 0 (null char), which also has to
be stored in the array.
Program 1
#include <iostream>
using namespace std;
int main ()
{
char x[5]={'a','b','c','d','e'};
cout<<x;
When you use the name of the array like that ('x'), it is converted
to a pointer to its first element (zeroth element, actually). Then,
it is treated as a C string. 'cout' is looking for the terminating
null char. Your array doesn't have any. That means outputting it
like that causes undefined behaviour.
}
Program 2
#include <iostream>
using namespace std;
int main ()
{
char x[5]={'a','b','c','d''};
You apparently have an extra single-quote char, probably because you
didn't copy-and-paste your code, but typed it in. OK, we'll consider
it a typo. Now, what's happening here? You declared the array to
have 5 elements and only provided 4 initialisers. All the elements
after the last initialiser are zero-initialised. So, after the four
characters in your 'x' array you have a *null char*.
cout<<x;
Outputting the array of char like that is *absolutely fine*, since it
is a true C string (a bunch of chars terminated with a null char).
}
Program 3
#include <iostream>
using namespace std;
int main ()
{
char x[5]="abcde";
I believe this is a syntax error. You provided 6- (yes, six-) char
literal as the initialiser for a 5-element array. That's too many
initialisers. Your compiler should refuse to compile that code.
The most common way to do what you seem to want here is this:
char x[] = "abcde";
which will make the size of that array 6 (the number of chars in
the initialiser literal, which contains the [hidden] null char at
the end).
cout<<x;
}
HTH
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask