1

In VS C++ I have a simple declaration of a char variable and a pointer to char.

char mychar = 'c';
char *mypointer = &mychar;

When printing the value of mypointer using cout I would expect an 8 character address value like 0038FEDC to appear in console. Instead I am getting some strange results like:

c│■8, ck∙<, c;■8 etc...

Why these strange characters appear when outputting pointer to char values?

  • 4
    Because `mypointer` is a `char *`, the `cout` system assumes it is a pointer to a null-terminated string of characters, so it prints the `c` that it does point to and all sorts of junk that belongs to other variables. You could try casting to `void *`; that should probably print as a pointer: `cout << (void *)mypointer << endl;` – Jonathan Leffler Mar 25 '15 at 06:59
  • @JonathanLeffler Thanks a lot. Your comment is as valuable as juanchopanza's answer. –  Mar 25 '15 at 07:14
  • 2
    Note that my C-style cast is sub-optimal for C++; you should probably use a `static_cast(mypointer)` instead. – Jonathan Leffler Mar 25 '15 at 07:16
  • @JonathanLeffler I wouldn't agree it is a duplicate. My question addresses a pointer to single character, not a pointer to null terminated constant string literals. –  Mar 25 '15 at 07:16
  • OK; we disagree. I guess it depends what you want. If you want to print a single character via a `char *`, then use `cout << *mypointer;` but if you expect an address (as your question suggests), then you have to request `cout << static_cast(mypointer);` or equivalent. You can't expect an address and then complain when you're told how to print an address instead of junk. Given your mention of expecting an address, I think the duplicate is appropriate. – Jonathan Leffler Mar 25 '15 at 07:19

1 Answers1

5

std::ostream, of which std::cout is an instance, has an overload for operator<< which treats char* as a pointer to the first character in a null-terminated string.

You are passing it a pointer of a single character, not a null terminated string. This causes undefined behaviour.

In practice what is likely to happen is that a stream of characters will be printed out by treating the memory starting from mychar as an array of char and iterating over it, until a \0 is found.

If you want to print the address, you can cast the pointer to something that isn't char*:

std::cout << static_cast<void*>(mypointer) << std::endl;
juanchopanza
  • 223,364
  • 34
  • 402
  • 480