What is the output of the following c++ code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

What is the output of the following c++ code?

char* a="coding"; char* b=(++a) + 3; cout<<*b; Answer: n Can anyone explain how the output is n?

9th Jun 2019, 7:25 PM
Rishu Kumar
Rishu Kumar - avatar
4 Answers
+ 10
Yes I think you have encountered this question in the c++ challenges. As you know that the characters of "coding" are stored in contiguous memory locations. Initially "a" is a character pointer which points to the first memory location which is "c". As "a" gets incremented it points to "o" and when 3 is added to the pointer it moves three more steps further and points to "n".
10th Jun 2019, 4:30 AM
Manoj
Manoj - avatar
+ 8
a points to c as the first letter of coding. after incrementing it points to o and after plus 3 it points to n.
9th Jun 2019, 7:32 PM
Thoq!
Thoq! - avatar
+ 7
In c++ a string is not (only) an array. It is a standard class that has its own behavior. I am not a c++ expert but I guess that either cout or the <<-operator is overloaded for input of type string. Maybe some of the c++-experts here can clarify this.
10th Jun 2019, 6:01 PM
Thoq!
Thoq! - avatar
+ 1
Uppala Manoj When i tried cout<<a; then coding was printed and when i tried cout<<b; then ng was printed so it seems like when we cout without * then wherever the pointer is from there till the end character is printed. But when i do this: int g[5]={1,2,3,4,5}; int* h=g; cout<<*h<<endl; cout<<h<<endl; then *h prints 1 so it's pointing to the first int here but h prints the address instead so why doesn't​ this happen with cout<<a; why does the whole coding gets printed instead of the address.
10th Jun 2019, 8:39 AM
Rishu Kumar
Rishu Kumar - avatar