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*/
3 Antworten
+ 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'.
+ 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.'