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;
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;
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 NUL
s 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