Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

format cout for pointer

Tags:

c++

pointers

cout

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?

like image 915
cadyT Avatar asked Dec 17 '22 02:12

cadyT


1 Answers

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.

like image 184
David Heffernan Avatar answered Jan 07 '23 22:01

David Heffernan