Search code examples
c++castingampersand

Confused by (char *) cast


struct myStruct
{
  int foo;
}

myStruct bar;
bar.foo = 123;
cout<<(char *) &bar<<endl;

The cout statement prints out '{'. The ASCII of 123 is actually '{' (bar.foo = 123. Changing this value around prints out different characters). What I don't understand is that

cout<<(char *) &bar<<endl;

should technically print the address of bar. How am I able to access the data inside the structure using a (char *) cast? Using (int *) still returns the address. I do know that a (char *) causes data to be arranged in a byte-by-byte fashion, but shouldn't that just affect the address?


Solution

  • There is an overload for << taking const char *, which interprets the operand as a pointer to a C-style zero-terminated string. That's the overload used by, for example

    cout << "Hello\n";
    

    If, as here, you give it a pointer to something other than a C-style string, you'll get undefined behaviour. In practice, it will print the contents of memory byte by byte until it reaches a zero-valued byte or walks off the end of readable memory.