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?
#include <iostream>
usingnamespace 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)
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;