0

I'm learning about pointers in C++. I wrote this simple program to show what I had a problem with:

#include <iostream>

using namespace std;

int main() {
    cout << "test1";
    char *ptr = 0;
    cout << ptr;
    cout << "test2";
}

When I run the program, it doesn't output "test2" at the end, instead only "test1". This should mean that it crashed when I tried to print out the value of ptr? I tried stepping through it in Eclipse debugger and it looks like every line gets executed but doesn't it throw an error or something?

tenkii
  • 449
  • 2
  • 10
  • 23
  • For starters, try this: cout << "test2" << endl; And see if it prints out test2. The previous line should print out the address of ptr. – kiss-o-matic Oct 10 '14 at 01:38
  • You are right -- sorry for my bad semantics. I'm not sure if it's implementation-defined though. I use this regularly with GCC on OSX & Linux. – kiss-o-matic Oct 10 '14 at 01:43

2 Answers2

3
char *ptr = 0;
cout << ptr;

There's an overload of the << operator that takes a char* operand, which it assumes is a pointer to a C-style string.

For pointer types other than char*, the << operator would print the value of the pointer (which is an address), but treating a null char* pointer as if it pointed to a C-style string causes undefined behavior. In any case, it's not going to print the pointer value.

To print the pointer value, you can convert it to void*:

cout << "test1\n";
char *ptr = 0;
cout << static_cast<void*>(ptr) << "\n";
cout << "test2" << "\n";;
Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
2

Normally you can output a pointer to cout and it will print the address contained. However, when you output a char * it is interpreted as a C-style null-terminated string. In this case, it's a null pointer and does not point to a string.

Try casting it to a void * before outputting it.

Neil Kirk
  • 21,327
  • 9
  • 53
  • 91