Why is char * pointer not showing

Hi everyone.

I have just started learning C++ and am playing with pointers. I think I understand the concepts, but whilst playing with pointers just now I have a question.

In the following code, I don't understand why the memory address for myChar is showing the same as the value itself. Why is it not giving me a memory location such as 0x123456 ?

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

using namespace std;

int main()
{
	int myInt = 0;
	int * intPointer = &myInt;
	
	char myChar = 'a';
	char * charPointer = &myChar;
	
	cout << "myInt value: " << myInt << "\n";
	cout << "Address of myInt: " << intPointer << "\n";
	
	cout << "myChar value: " << myChar << "\n";
	cout << "Address of myChar: " << charPointer << "\n";
	
	return 0;
}


Program Output:

1
2
3
4
myInt value: 0
Address of myInt: 0xbfe9d884
myChar value: a
Address of myChar: a


I thought that I would have to specifically dereference charPointer in order to get the value that is points to?

Many thanks for your help.
when the << operator sees a char* is assumes you are working with a char array
because when you pass a char array to a function it decays to a pointer. you can try casting the char* to a different type of pointer such as void*.

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

using namespace std;

int main()
{
	int myInt = 0;
	int * intPointer = &myInt;

	char myChar = 'a';
	char * charPointer = &myChar;

	cout << "myInt value: " << myInt << "\n";
	cout << "Address of myInt: " << intPointer << "\n";

	cout << "myChar value: " << myChar << "\n";
	cout << "Address of myChar: " << (void*)charPointer << "\n";

	cin.ignore();
	return 0;
}
Last edited on
Wow.. I wouldn't ever have guessed that's why it wasn't working!

So by casting the char* pointer into a generic void pointer, the << operator kind of 'gives up', and no longer assumes you've given it a character array, and thus does what I expected it to. I see... So the << operator is just a part of the C++ language designed to work like that?

Thanks for the information.. I shall try to remember it..

Cheers
Its just because the operator << is overloaded so that when you have something like char intro[14] = "Hello, World!"; you can output it like: std::cout << intro << std::endl; instead of getting a memory address and having to do something like:
1
2
3
4
5
6
7
for( int i = 0; i  < SIZE; ++i )
    std::cout << intro[i];
std::cout << std::endl;

for( int i = 0; intro[i]; ++i )
    std::cout << intro[i];
std::cout << std::endl;


*fixed slight bug
Last edited on
Topic archived. No new replies allowed.