0
int main() {
    int x = 69;
    int* px = &x;
    cout << px << "\n" << *px << "\n\n";

    float z = 69.69;
    float* pz = &z;
    cout << pz << "\n" << *pz << "\n\n";
    
    char y = 'y';
    char* pc = &y;
    cout << pc << "\n" << *pc;
    return 0;
}

This outputs:

004FFD28
69

004FFD10
69.69

y╠╠╠╠╠╠╠╠²O
y

Why does the char pointer have some weird value that's not a number?

  • You have a `char*` which points at _one_ `char` but you try to print a null terminated string - that causes undefined behavior. To print the pointer value, try `std::cout << reinterpret_cast(pc);` – Ted Lyngmo Apr 01 '21 at 12:07
  • Because the string pointed by `pc` is not NUL terminated. Read the chapter dealing with strings in your C text book – Jabberwocky Apr 01 '21 at 12:07
  • cout treats "pc" as a string pointer and strings are supposed to end with \0 thus you see garbage – AndersK Apr 01 '21 at 12:07
  • What output did you expect BTW? – Jabberwocky Apr 01 '21 at 12:10
  • @Jabberwocky, I though it would print something like 004FFD28, I think I'm not understanding something really fundamental about pointers and/or how chars are stored in memory – Hayden Soares Apr 01 '21 at 12:17
  • Then the [duplicate question](https://stackoverflow.com/questions/17813423/cout-with-char-argument-prints-string-not-pointer-value) contains your answer. – Jabberwocky Apr 01 '21 at 12:20
  • @HaydenSoares The confusion is understandable and the dupicate answers it, even if the top answers doesn't do it very directly. One of the answers at the bottom ([this one](https://stackoverflow.com/a/54256587/7582247)) gives the reason. – Ted Lyngmo Apr 01 '21 at 12:26

1 Answers1

0

Outputting a char * value is interpreted as outputting a C-style 0-terminated string. Which your pointer does not point to, so you get garbage.