Then what does a+1 refer to?
a
points to the first element of the array str
. The value of the first character is 'A'
. The result of a + 1
expression is a pointer to the next element of str
after the one that a
points to. The next element is the character with the value 'B
'.
This confusion has dawned in me because when I give:
cout<<a+1;
It gives me BC instead of B, why is it like that?
This is because when you insert a pointer to a character into a character stream (such as std::cout
), it is assumed to point to a character in an array (as it does in this case), and the behaviour is to stream all characters in that array until the null termination character (\0
) is reached.
So, just like when you insert the pointer that points to A
and all characters starting from A
until the null termination character are printed (ABC
), similarly when you pass the pointer that points to B
then all characters starting from B
are printed (BC
).
You can dereference the pointer to insert just that one character, if that is your intention:
std::cout << *a; // A
std::cout << *(a + 1); // B
or
std::cout << a[0]; // A
std::cout << a[1]; // B