Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ get address of variable without operator&

Tags:

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?

like image 987
Ashot Avatar asked Oct 30 '14 13:10

Ashot


People also ask

How will you print the address of a variable without using a pointer?

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.

How do you find the address of a variable?

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.

What is the address of a variable in C?

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.

How do you print the address of a pointer in C?

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.


2 Answers

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.

like image 69
Mike Seymour Avatar answered Sep 17 '22 15:09

Mike Seymour


Since C++11, you may use the function std::addressof

like image 21
Jarod42 Avatar answered Sep 17 '22 15:09

Jarod42