I want to convert these c code to c++ code . It is about pointer printf
int n = 44;
//printf("n = %d \t &n = %x\n", n, &n);
cout<<"n ="<<n<< "\t" <<"&n ="<<hex<<int(&n)<<endl;
When I run the printf output is like that:
n=44 &n=22ff1c
But when I run the cout output is like that:
n=44 &n=22ff0c
Why do the two versions output different values for the address of n?
The compiler happens to put the stack allocated variable at a different location in the different versions of the program.
Try including both printf and cout versions in the same program so that they work with the exact same pointer. Then you will see that the two versions behave the same way.
int n = 44;
printf("n = %d \t &n = %x\n", n, &n);
cout<<"n ="<<n<< "\t" <<"&n ="<<hex<<int(&n)<<endl;
As Mr Lister correctly points out, you should use the %p format string when printing pointers in printf.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With