Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Why this code works?

C++
char* ch="hello";
cout<<ch;


I thought we can only store single characters (char ch='a' or '3' or '$') or ASCI numbers (char ch= 65) in a character container. But when I use a character pointer, I can store a string in it. How is this possible? And is there other things I don't know about chars?
Posted

You seem to not know the basics of pointers and string literals in C/C++.
I suggest to work through some tutorial on C/C++, e.g., Character Sequences[^] and Pointers[^]. Or even better, go through all parts of the C++ Language[^] tutorial (or any similar reference).

For the particular case:
1. "hello" is a sequence of 6 characters: h,e,l,l,o plus the terminating zero character.
2. that sequence of characters is accessible through the memory address of the first character of the sequence
3. that address is stored in a pointer variable
4. in C/C++ you write a pointer to a type as type * var = ...;, e.g. char * s = "hello";
5. naming a pointer to character as ch is fooling everyone - name it greeting or alike

Cheers
Andi
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 26-Jul-14 1:34am    
Makes sense, a 5.
—SA
Andreas Gieriet 26-Jul-14 14:14pm    
Thanks for your 5!
Cheers
Andi
char * is different from char. char * represents a pointer to a storage location that holds a string.
char is simply storing the character value.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 26-Jul-14 1:38am    
Strictly speaking, char * just points to a character or just any data, because any byte of data could be considered as a character. It does not tell what is supposed to be next to this character in memory. You could call it a string if you want...
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900