Skip to content

Address Operator

Address Operator

An address-of operator is a mechanism within C++ that returns the memory address of a variable. These addresses returned by the address-of operator are known as pointers, because they "point" to the variable in memory.

1
2
3
4
int a = 10;
cout << "a: " << a << '\n';
cout << "&a (hex): " << &a << '\n';
cout << "&a: (dec) " << reinterpret_cast<uintptr_t>(&a) << '\n';

1
2
3
4
int b = 10;
cout << "b: " << b << '\n';
cout << "&b (hex): " << &b << '\n';
cout << "&b: (dec) " << reinterpret_cast<uintptr_t>(&b) << '\n';

1
2
3
4
auto c = std::make_unique<int>(10);
cout << "*c: " << *c << '\n';
cout << "c (hex): " << c << '\n'; // address should be distant from a and b
cout << "c: (dec) " << reinterpret_cast<uintptr_t>(c.get()) << '\n';

1
2
cout << "Distance &b - &a = " << &b - &a << " ints\n";
cout << "Distance &b - &a = " << reinterpret_cast<unsigned char*>(&b) - reinterpret_cast<unsigned char*>(&a) << " bytes\n";

1
2
cout << "Distance c.get() - &a = " << c.get() - &a << " ints\n";
cout << "Distance c.get() - &a = " << reinterpret_cast<unsigned char*>(c.get()) - reinterpret_cast<unsigned char*>(&a) << " bytes\n";

Share Snippets