+ 5

Please tell me how it ends like this..

#include <iostream> using namespace std; int main() { char * c="c+"; cout<<c; c++; cout<<c; return 0; } //output: c++ It is one of the challenges I met. I have no idea now..

12th Jun 2017, 6:34 AM
Philip
Philip - avatar
7 Answers
+ 12
well a lot of people have difficulties with pointers, I don't like them either. The key to this is in char * c = "c+" two things happen in that line you get "c+" put somewhere in the memory and the variable c which holds the memory address of it. the first cout prints "c+", then you move the pointer to the right and it no longer points at the beginning but to the "+", that's why the second cout prints only +. When you collect the two outputs you get: "c+" + "+" = "c++".
12th Jun 2017, 7:08 AM
Nikolay Nachev
Nikolay Nachev - avatar
+ 7
@branko - that actually is a question which requires knowledge in C++ and the way it uses pointers more advanced than mine... @Hatsy, @Ace, @Valentine - a bit of help here...
13th Jun 2017, 7:27 AM
Nikolay Nachev
Nikolay Nachev - avatar
+ 6
@branco - you triggered my curiosity, so I did some research. Seems like this is how << of cout works when you pass a char pointer (trying to be clever and assuming that in this case you want to print the whole string). Seems like that is something inherited from the way C handles strings and if you actually need the address you need to create pointer to that pointer. If anyone can explain it better I would also love to read that explanation 😆
13th Jun 2017, 1:55 PM
Nikolay Nachev
Nikolay Nachev - avatar
+ 3
Wow it's amazing!!! you opened my eyes!!!Thank you!!wowowowowow
12th Jun 2017, 7:15 AM
Philip
Philip - avatar
+ 2
@Nikolay Nachev why doesn't "cout <<c" print the memory location stored in the pointer? I thought you would have to dereference the pointer to get the "c+" inside the variable to output instead?
13th Jun 2017, 6:36 AM
Aeedoom Aeedad
Aeedoom Aeedad - avatar
+ 2
@Nikolay Nachev that's really interesting haha, I definitely need to read up some more on pointers as well, thanks for the information!
13th Jun 2017, 2:20 PM
Aeedoom Aeedad
Aeedoom Aeedad - avatar
+ 1
This is an example of what is called "pointer arithmetic." Here is a picture of how the pointer looks in memory: Memory... | C | + | memory... ^ Pointer is pointing to the first character in the string. When the first cout command is issued, it outputs what the pointer is currently pointing to (c in this case). When the command c++ is issued, the pointer advances in memory to the next character in the string. Here is a picture of what the pointer looks like in memory after the c++ command : Memory... | C | + | memory... ^ Pointer is now pointing to the + character. So, when the next cout command is entered, the character that the pointer is pointing to (which is now +) is outputted. Hope this helps, let me know if you have more questions!
13th Jun 2017, 7:47 PM
Ashton Durrant
Ashton Durrant - avatar