understanding character pointers

I was expecting the cout to print addresses since b and d are pointers, but only b prints the value and not the address, why is that?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main()
{
  
  char a[] = "abcd";
  char* b = a;
  
  char c = 'c';
  char* d = &c;
    

    cout << b << d << endl;
    return 0;
}
Last edited on
<< is effectively shorthand for a function, operator<< that accepts a char pointer.

There are many other versions of the same function that accept other kinds of parameter.

It was decided, when creating C++, that the operator<< here that accepts a char pointer will NOT output the value of the char pointer, but will instead output the character it's pointing at, and all the subsequent characters in memory until it hits a zero.

This was a deliberate choice, because it's so common to want to output an array of characters that has a zero on the end of it, because in C that's what a string is, and you keep track of them by holding onto a pointer to the first character.

Note that when you do this: cout << d you've got a problem because d is a pointer to a char that does NOT have a zero right after it, so you're going to keep reading whatever memory is after that char and outputting it. Might be nonsense, might be some other variable, might just crash.
Last edited on
Just cast b d to say long int (or long long int for x64). It will then display the address. You might want to also use std::hex to get the address display in hex rather than decimal.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <iomanip>

int main()
{
	char a[] = "abcd";
	char *b = a;

	char c = 'c';
	char *d = &c;

	std::cout << std::hex << reinterpret_cast<unsigned long>(b) << "  " << reinterpret_cast<unsigned long>(d) << '\n';
}



18ff34  18ff33

Topic archived. No new replies allowed.