I have got a class that has overloaded unary operator&
. The objects of that type were created using new
, so address of variable was accessible but now I need to use static object. Is it possible to get its address?
To print the memory address, we use '%p' format specifier in C. To print the address of a variable, we use "%p" specifier in C programming language.
To access address of a variable to a pointer, we use the unary operator & (ampersand) that returns the address of that variable. For example &x gives us address of variable x.
When a variable is created in C, a memory address is assigned to the variable. The memory address is the location of where the variable is stored on the computer. When we assign a value to the variable, it is stored in this memory address.
You can print a pointer value using printf with the %p format specifier. To do so, you should convert the pointer to type void * first using a cast (see below for void * pointers), although on machines that don't have different representations for different pointer types, this may not be necessary.
In C++11 or later, std::addressof(object)
, declared by the <memory>
header.
Historically, it was more grotesque, especially if you wanted to deal with const
and volatile
qualifiers correctly. One possibility used by Boost's implementation of addressof
is
reinterpret_cast<T*>( &const_cast<char&>( reinterpret_cast<const volatile char &>(object)))
first adding qualifers while converting to char&
so that reinterpret_cast
would work however object
were qualified; then removing them so that the final conversion would work; then finally taking the address and converting that to the correct type. As long as T
has the same qualifiers as object
(which it will as a template parameter deduced from object
), the resulting pointer will be correctly qualified.
Since C++11, you may use the function std::addressof
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