1

I don't think there is much context needed for this question, so I exclude the rest of the code that I think is irrelevant. I type the code below and yet the console prints: "ü vaqB A". So the console misprints only the "cout << "MyPtr: "" part. I don't understand why this happens.

    #include <iostream>
    using namespace std;

    int main() {
    char var = 'A';
    char *MyPtr = &var;
    cout << "MyPtr: " << MyPtr << endl;

}
Lucas C
  • 11
  • 3
  • 4
    Because your pointer points to a single character, not a nul terminated string. – Retired Ninja Jun 12 '19 at 02:03
  • Try `cout << "MyPtr: " << *MyPtr << endl;` instead: https://ideone.com/GqHcYI – drescherjm Jun 12 '19 at 02:16
  • When you give it a `char*` the output is printing a string (which needs to be null terminated) instead of the address of the character like it would with other pointers. This is a specialization for `char*` to print cstrings. Follow the link above this comment for more info on this. – drescherjm Jun 12 '19 at 02:51
  • If you want to print the address that a `char*` pointer is pointing at, you need to cast it to `void*` when passing it to `operator<<` – Remy Lebeau Jun 12 '19 at 03:10

0 Answers0