简体   繁体   中英

how to find allocated memory by a variable?

class app {
        public int x = 3; 

        static void Main(string[] args)
        {
        }
}

it's possible get the memory address allocated by x variable?

the example can be in C , C++ , C# or D . I hope it is clear Thanks in advance

In C and in C++ this is fairly straight-forward. I'll give the example in C++:

struct App
{
   int x;
   App() : x(3) { }
};

int main()
{
  App a;
  int * p = &a.x; // address goes here
}

There is of course no such thing as "the variable App::x ", since App is only the type . Each instance of this type, such as a in the example, carries its own set of member variables, and a pointer to the member variable is readily obtained. (The same is true for plain data structs in C.)

Note that C++ has another, related feature: Member pointers. This allows us to form the opaque value int App::*pm = &App::x which by itself doesn't point to anything, but only carries information about the offset of App::x inside the class, if you will. This animal can be used together with an instance to obtain the actual value, eg a.*pm .

The ampersand ( & ) is the "address-of" operator in most C-like languages:

int x;
printf("Address of x is %p\n", &x);

The return value of & is effectively a pointer to its operand.

Skipping D and E. C# and F# (and other CLR languages) - there is no fixed addres for any partcular variable in general. One can use managed debugger (ie WinDbg + SOS) to find address of any particular variable, or use fixed along with interop classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM