defining a string in C++ with const char *str="Hello";

526 views Asked by At

I am a little confused here. In the statement const char *str="Hello";, str is a pointer to a char variable pointing to the first character 'H' of the string "Hello", so str should contain the address of the 'H' character. And yet, if I use cout<<str, it prints the entire string "Hello" and not the address.

And also, If I use cout<<*str to print the value stored in the address pointed to by str, it prints the char 'H' correctly.

Can someone please explain how and why this happens? This may be very basic, but an explanation would help me understand these concepts more clearly.

1

There are 1 answers

0
eerorika On

str is a pointer to a char variable

There is no char variable in the example. str does point to a char object.

Can someone please explain how and why this happens?

Because the binary operator << whose left hand operand is an output sream and right hand operand is a pointer to char is specified to print the entire string.

If the pointed char isn't within an array that contains the null terminator character starting from that character, then the behaviour of the program would be undefined. String literals are null terminated, so the example is correct.