Anomalous output of outputting the address of char variable

code :
#include

using namespace std;

int main() {
char c = ‘a’;
char * p = &c;
cout<<p<<endl;
cout<<&c<<endl;
cout<<(void*)&c<<endl;
cout<<(int*)&c<<endl;

// cout<<"Sum of x+y = " << z;
return 0;

}
Output:

a?Ge��
a?Ge��
0x7ffec265473f
0x7ffec265473f

According to the explanation given in the video I should have got a as output after doing cout<<&c<<endl;
but I am getting some sets of character why this is so. please explain why I am getting all these characters.

Hello @Divya_321,

When you try to print the address of char variable using ‘&’(address of operator), it keeps on printing the characters present in the memory after the current location until it encounters a NULL or ‘\0’ character.

As we can see variable c has assigned a memory location: 0x7ffec265473f
So, when you do cout<<p<<endl; or cout<<&c<<endl;
The compiler is first printing the character present at 0x7ffec265473f i.e. ‘a’
then, it checks for next memory location 0x7ffec2654740 which contains ‘?’ and print it
Similarly, it prints the characters present at 0x7ffec2654741, 0x7ffec2654742, 0x7ffec2654743 and 0x7ffec2654744 i.e. ‘G’, ‘e’, ‘�’ and ‘�’ resp.

Now, it reaches the location 0x7ffec2654745 and it contains ‘\0’ character.
So, the further execution terminates.

To avoid this.
You are required to typecast this operator as you have done in the last two cout statements.

Note:
IT is possible that you may get different characters attached after ‘a’ for different executions of code or for executing it on different compilers.
You can also get ‘a’ as an output for the case when the next location contains ‘\0’ character.

Hope, this would help.
Give a like, if you are satisfied.

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

1 Like

I am satisfied with your explanation and have liked it, but I don’t see here any rating meter to rate, so just cliked on the like icon

@Divya_321,

You get that option when you mark a doubt as resolved.
Thanks, for the like.