Unusual behaviour with character pointers
In C++, cout shows different printing behaviour with character pointers/arrays unlike pointers/arrays of other data types. So this article will firstly explain how cout behaves differently with character pointers, and then the reason and the working mechanism behind it will be discussed.
From the above code, it is clear that:
- When using the integer pointer to an array, cout prints the base address of that integer array.
- But when the character pointer is used, cout prints the complete array of characters (till it encounters a null character) instead of printing the base address of the character array.
In this example as well, the character type pointer c is storing the base address of the char array b and hence when used with cout, it starts printing each and every character from that base address till it encounters a NULL character.
abc a a
In the above example, c is a simple character variable and it prints the value stored in it as expected. p being a character pointer when used with cout, results in the printing of each and every character till a null character is encountered. Thus, some garbage value is being printed after ‘$’. This simply means that in the memory the null character was placed after the ‘a’ character (since in this case, there is no automatic storing of a null character after the useful piece of data is finished unlike character arrays) and so it stops printing and gives the obtained output.
Reason behind unusual behaviour with character pointers:
The reason for this lies in the concept of Operator Overloading. ‘<<‘ operator is overloaded for different types of inputs. In the case of const void* overload, it prints just the address. But for const char* overload, it starts printing each and every character till it encounters a null character (treating the input as C — style string).
abc a a
Explanation:In the above example:
- Only ‘c’ with cout is treated as const char * and << operator overload for such input is called and thus every character is printed until null character.
- When using c, i.e., *(c + 0), it simply dereferences the particular memory location and prints the value stored at that location only.
- Similarly, for *c which is same as *(c + 0).
NOTE: The unusual behaviour can be rectified if the output is type casted into something which will not be treated as C-style string.
In the above example, the base address of the character array is obtained in the output.
Utilization of unusual behaviour with character pointers:
Given a string, print the pattern as shown in the following example:
d cd bcd abcd