-1

This code is giving output "AA".Why not this code prints "A"?

    int i = 65;
  char c = i;
  int *p = &i;
  char* pc = &c;
  cout << pc << endl;

1 Answers1

6

i is on the stack "after" c; when you print a char* it treats it as a NUL-terminated string. Your machine is little-endian, so the memory layout is:

65 65 0 0 0
 c  i i i i

which, since 65 is the ASCII ordinal for the letter A, reads like a string "AA" (with a couple extra trailing NULs that get ignored), and is printed as such. The result of reading beyond c from the pointer is undefined behavior, and works only by coincidence (you got lucky on how the compiler laid out the memory); never, ever rely on it.

If you only wanted to print A, just dereference pc when printing it:

cout << *pc << endl;
        ^ dereferences pc to print only the single character it points to
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • 1
    Relevant: https://stackoverflow.com/questions/17813423/cout-with-char-argument-prints-string-not-pointer-value. Also good point about the UB and coincidence: On my machine, it looks like it doesn't place `i` and `c` next to each other, and it prints `A╠╠╠╠╠╠╠╠A` instead of `AA` because of the variation in exact memory layout. – Nathan Pierson Sep 26 '20 at 16:38
  • 2
    @NathanPierson: And in all likelihood, some combination of compiler options (related to stack safety, variable alignment, etc.) would make it not work on the OP's machine, or work on yours. It's not worth the risk of nasal demons either way. – ShadowRanger Sep 26 '20 at 16:39