Click here to Skip to main content
15,507,379 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
char * p = "hello";


Can any one explain the first two outputs please?
Updated 9-Sep-11 10:43am
Philippe Mori 9-Sep-11 18:27pm    
Are you sure that your second line is 105? If so, your compiler is broken.

Something strange, here:
according to the standard, your compiler and or the standard library aren't standard, or ... you did a typo.

The key is the << operator between cout and the expressions.
p is a char*, and << sends out the sequence of character it points to up to the '\0' implicitly appended to the definition of the "hello" literal (hence, it prints hello).
p+1 is a char* pointing to the next of "h", and works the same as before (hence , should had been printing ello.
*p is a character, and << just prints it.
*p+1 is an expression that evaluates to an integer: *p is the char 'h', and + between a char and an int promotes the char as int and adds the integers. 'h' is 104, adding 1 gives 105 (and it's printed).
Share this answer
Simon Bang Terkildsen 9-Sep-11 17:31pm    
+5 Glad to hear it was not just me who thought that was strange. Probably a typo or a weird compiler.
Sergey Alexandrovich Kryukov 10-Sep-11 0:08am    
Horse is really around the corner -- I'm not a psycho... :-)
Now we know that "ello" == 105 (a world constant, almost :-)
My 5 to Emilio, too.
Emilio Garavaglia 10-Sep-11 2:56am    
"Horse is really around the corner": ??? My reference culture does not contain such an expression. What does it mean? (Of course, that's off-topic, do not answer if you find that's not the case!)
[no name] 12-Sep-11 4:20am    
Good one. My 5 too.
1) p is a pointer to a character array and giving it to cout will print the contents as a string
2) p+1 is evaluated as a contents of the first char in the array + 1 ie h=104 + 1
3) *p means the contents of the address the pointer is pointing to which is a character which is h
Share this answer
Simon Bang Terkildsen 9-Sep-11 16:07pm    
about 2) that must depend on your compiler, as I would expect it to print "ello" and I've just tried it with VC++ and I get "ello". cout<<*p+1; prints 105
Philippe Mori 9-Sep-11 18:26pm    
Effectivelly, it should print "ello". Thus answer #2 is not valid.
Sergey Alexandrovich Kryukov 10-Sep-11 0:10am    

HELLO! this my greeetings!!!

I ran ur code in vc2005. my pc has win 7..

char * p = "hello";
cout<<p;   // printing the char pointer wihtout any condition
cout<<p+1; // printing the pointer skipping the first character
cout<<*p;// printing the value at the address char p[0]. which is p[0].

I got the following anwser which is as expected:


please re-build the project and try again!
Share this answer

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