Why is the rest of the string printed (C++)? &s[i] | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why is the rest of the string printed (C++)? &s[i]

Playing a little bit, I found out a way to print the rest of the string by having a position to start. Here's the code: https://code.sololearn.com/ca3a2A15A237 But honestly I don't understand why this works, writing &s[5] I was expecting to print the memory address of that particular character at that position, but instead, prints "programmers!!!", why is this happening? Why the & have that effect in the array? Why is not printing only the memory address at that position?

22nd Jan 2021, 6:46 AM
Eduardo Perez Regin
Eduardo Perez Regin - avatar
2 Answers
+ 3
If you try to print a char* (char pointer), C++ will print the values of all character addresses after the char pointer till a null character ('\0') is encountered. For this reason in your program, when you try to print &s[5], which is a char*, it prints all the characters in the memory addresss after &s[5] till a null character is found (which is automatically added by C++ to a double-quote enclosed string). This happens with char pointers only. Try making an int array and doing the same thing, it will print the memory address. If you want to print the memory address of s[5] in your program you need to cast the char* to int*, like so std::cout << (int*)&s[5] << '\n';
22nd Jan 2021, 7:13 AM
XXX
XXX - avatar
0
XXX I see, that seems to have sense, I was expecting printing the memory address because & operator. Also I tried to do the same thing to an int array and only prints the memory address. Thank you for yoour explanation! :D
22nd Jan 2021, 7:58 AM
Eduardo Perez Regin
Eduardo Perez Regin - avatar