Reputation: 77
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?
Upvotes: 4
Views: 16339
Reputation: 613352
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.
Upvotes: 11
Reputation: 61625
You do not control where n
is in memory. The compiler may change how things are positioned depending on other things that seem unrelated. It does not matter. You are not entitled to say where n
should go; something else might already be where you want to put it.
Upvotes: 1
Reputation: 44706
Assuming that you don't mean the whitespace differences. The address where n
is allocated on the stack is different in each run of the program. Otherwise, it all looks OK to me!
Upvotes: 0