Displaying the Address of Chars

So we have an assignment in my C++ class to create a pointer to a char and the instructions are:

For each declaration make sure to:
a) initialize the pointer to an appropriate address value
b) show the contents of the pointer (match this value with the address of what is pointing to)
c) show the contents of what the pointer points to (match this value with the original contents)

Whenever I try to display the address of char a with &a , it just outputs the value stored in char a rather than the address. When I try this with integers it works like I want it to.

Can anybody give me an idea as to what I'm doing wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

using namespace std;

int main()
{
    
    // Question 1, Part I
    
    // (a)
    char a = 'A';
    
    char * pa = &a;
    
    //(b)
    cout << "Address of a = " << &a << endl;
    cout << "Contents of pa = " << pa << endl;
    
    //(c)
    cout << "Contents of a = "<< a << endl;
    cout << "What pa points to = "<< *pa << endl;

    return 0;
}
A character pointer is interpreted as a c-string by ostream operator << so it will output until a null terminator is found. You could try casting it to a void pointer. try (void*)&a or static_cast<void *>(&a)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

using namespace std;

int main()
{
    
    // Question 1, Part I
    
    // (a)
    char a = 'A';
    
    char * pa = &a;
    
    //(b)
    cout << "Address of a = " << (void*)&a << endl;
    cout << "Contents of pa = " << static_cast<void*>(pa) << endl;
    
    //(c)
    cout << "Contents of a = "<< a << endl;
    cout << "What pa points to = "<< *pa << endl;

    return 0;
}
Address of a = 0x7fff3a5dbc77
Contents of pa = 0x7fff3a5dbc77
Contents of a = A
What pa points to = A
Last edited on
The stream operators are specialized to deal with char const * as a c-style string. Cast the point to a void const * to force displaying the address.
1
2
char c = 'h';
std::cout << static_cast<void const *>(&c) << std::endl;
operator<< for ostream has special overload for char pointers. It treats them as c-strings. You just got luckt hat it was not worse. Here what it shows for me:
Address of a = A7■"
Contents of pa = A7■"
Contents of a = A
What pa points to = A
Solution would be to cast char pointer to void pointer:
cout << "Address of a = " << static_cast<void*>(&a) << endl;

Edit: Ninja army :)
Last edited on
Great! Thanks for your help guys :D
Topic archived. No new replies allowed.