Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

understand how char works in c++

I am a C++ newbie. Although many similar questions have been asked and answered, I still find these concepts confusing.
I know

char c='a'            // declare a single char c and assign value 'a' to it
char * str = "Test";  // declare a char pointer and pointing content str, 
                      // thus the content can't be modified via point str
char str1[] = "Test"; // declare a char array str1 and assign "Test" to it
                      // thus str1 owns the data and can modify it

my first question is char * str creates a pointer, how does char * str = "Test"; work? assign a string literal to a pointer? It doesn’t make sense to me although it is perfectly legal, I think we can only assign an address to a pointer, however "Test" is a string literal not an address.

Second question is how come the following code prints out "Test" twice in a row?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

char str2[] = {'T','e','s','t'};  // is this line legal? 
                                 // intializing a char array with initilizer list, seems to be okay to me
cout<<str2<<endl;               // prints out "TestTest"

why cout<<str2<<endl; prints out "TestTest"?

>Solution :

char * str = "Test"; is not allowed in C++. A string literal can only be pointed to by a pointer to const. You would need const char * str = "Test";.

If your compiler accepts char * str = "Test"; it is likely outdated. This conversion has not been allowed since C++11 (which came out over 10 years ago).


how does char * str = "Test"; work?

String literals are implicitly convertible to a pointer to the start of the literal. In C++ arrays are implicitly convertible to pointer to their first element. For example int x[10] is implicitly convertible to int*, the conversion results in &(x[0]). This applies to string literals, their type is a const array of characters (const char[]).


how come the following code prints out "Test" twice in a row?

In C++ most features related to character strings assume the string is null terminated, which is implied in string literals. You would need {'T','e','s','t','\0'} to be equivalent to "Test".

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading