0
What's the output of this code AND WHY / EXPLAIN
char* p = "hello" int n =1; cout << *(p + --n);
1 Answer
+ 3
I'll try to explain, but if you are new to pointers, it can be difficult to understand.
---
p is a pointer that points to the memory address of first element of the character array.
So writing cout << p; would output a memory address. To output the value of that address, use dereference operator *
i.e. cout << *p; will output "h"
when you write *(p+n), you are accessing the nth element's value. In this code *(p+1) would output "e" because it's the next element in the sequence.
In this code, *(p + --n) = *(p + 0) = *p, so it will output h
To learn more about pointers, watch tutorials on youtube or google about them. It can be a hard topic to learn, but when you understand it, it becomes easy :)