Why this code prints “llo” as an output? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why this code prints “llo” as an output?

I came across this example in a challenge but I dont really understand how it adds value to a string pointer. Please help me to explain this. Thank you very much. Char* pString=“Hello”; pString+=2; Printf(pString); /*llo*/

24th Jan 2020, 9:06 AM
Nemui
3 Answers
+ 12
char* pString = “Hello”; character pointer pString points to the first character in the string literal "Hello", 'H'. pString += 2; character pointer pString incremented by 2, now points to *(pString + 2), which is two characters after 'H'. The pointer now points to the first 'l' of "Hello". printf(pString); prints the c-style string begining from where the pointer is pointing to, to the end of the string denoted by the null character, '\0'.
24th Jan 2020, 9:15 AM
Hatsy Rei
Hatsy Rei - avatar
+ 6
pString is a pointer that points to the first letter of a string "Hello" that lies in memory somewhere. Pointers can be changed to point somewhere else. printf with "%s" takes such a char pointer and reads until it finds a 0 ('\0') in that array. If you increase that pointer by 2 and give it to printf like this, it basically means: 'Read that string from position 2, till you get to the end marker.'
24th Jan 2020, 9:11 AM
HonFu
HonFu - avatar
+ 2
HonFu Hatsy Rei thank you very much, those explaintions are really helpful !
25th Jan 2020, 3:54 PM
Nemui