-1
#include<iostream>
#include<cstdlib>
using namespace std;

int main()
{
    int temp = 300;

    cout << "Address of variable temp:  " << (unsigned)&temp;
    return 0;
}

main.cpp: In function ‘int main()’: main.cpp:17:57: error: cast from ‘int*’ to ‘unsigned int’ loses precision [-fpermissive] cout << "Address of variable temp: " << (unsigned)&temp;

Tschallacka
  • 27,901
  • 14
  • 88
  • 133

2 Answers2

3

You convert a pointer to int to an unsigned int.

The problem is that an unsigned int is too little to contain all possible values of a pointer to int.

You can try with an unsigned long long that should be great enough

(unsigned long long)&temp;

You can check the dimension of the type with sizeof(), that return the number of bytes of a type/variable

With my platform (Linux amd64) from

std::cout << sizeof(&temp) << std::endl;
std::cout << sizeof(unsigned) << std::endl;

I get 8 (for sizeof(&temp)) and 4 (for sizeof(long)).

And, obviously, a 4 bytes variable can't represent all possible values of a 8 bytes variable.

From a different platform you can get different values.

max66
  • 65,235
  • 10
  • 71
  • 111
2

Not sure, why you are trying to cast it. But if you are trying to see the memory address of temp then you should do &temp.

#include<iostream>
#include<cstdlib>
using namespace std;

int main()
{
    int temp = 300;

    cout << "Address of variable temp:  " << &temp;
    return 0;
}
Geno C
  • 1,401
  • 3
  • 11
  • 26