output pointer to char and output pointer to int

when I run the code below, I got the result after the double slash.
it seems that when i output a pointer to int, it outputs the address in the pointer, but when i output a pointer to char, it outputs an array of chars in which the last char is a white space. Why!?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>

using std::cout;
using std::endl;

int main()
{
    char p[] = "hello";
    cout<<*p<<'\n';             // h
    cout<<p<<'\n';              // hello

    char c = 'a';
    char *pa = &c;
    cout<<*pa<<'\n';            // a
    cout<<pa<<'\n';             // ahello

    int i = 2;
    int *pi = &i;               
    cout<<*pi<<'\n';            // 2
    cout<<pi<<'\n';             // 0x22fefc
}

Last edited on
The C++ programming language simply specifically states that when you pass a char-pointer to cout through the << operator, it will output the char at that address and all following chars until it finds the value zero.

When you pass an int-pointer to cout through the << operator, it will output the value of the pointer (i.e. the address of the int that is being pointed at).

This is simply how the language works. In this case, a char-pointer is treated fundamentally differently to an int-pointer.

The reason behind this is (probably) historical. In C, a char-pointer is how one keeps hold of a string, so when someone passes a char-pointer to cout, they probably want that string to be output. It's a convenience provided to you by the language designers.

If you really do want the value of the char-pointer (i.e. the address of the char being pointed at) you can still get that.
Last edited on
A c-string is, in this context, a pointer-to-char. It would be awkward if the default behavior of std::cout was to print the address contained in a pointer-to-char rather than the string the user expected. A pointer to int, on the other hand, never points to a c-string, so there's no reason not to print the contained address.

If you want to print the address for a pointer-to-char, the usual way is to cast it to void*;

std::cout << (void*)pa << '\n' ;


Your line 15, btw, results in undefined behavior.
@Moschops Thank you so much for replying soon and i can understand the difference now!

so, maybe the << operator for char-pointer is specially overloaded to cater to previous C languages.

Topic archived. No new replies allowed.