Weird reference behaviour (Same memory address of int)
Hy! Iam learning refference types now, and I dont get it why does x has the same memory address as y? Shouldn't they have different addresses?
class Program
{
static void Main(string[] args)
{
int x = 10; // int -> stack
int y = x; // assigning the value of num to mun.
DisplayMemAddress(x);
DisplayMemAddress(y);
Console.ReadLine();
}
static unsafe void DisplayMemAddress(int x)
{
int* ptr = &x;
Console.WriteLine("0x" + new IntPtr(ptr).开发者_如何转开发ToString("x"));
}
}
x
and y
in Main
are independent variables. They can store different values. They can't be at the same address. Note that they're value type variables though - you're not actually learning about reference types at all in this code, as it doesn't use any reference types (except string
, Program
and Console
).
However, your code doesn't show that - it's showing the address of the parameter in DisplayMemAddress
, which is entirely different. The values of x
and y
are passed by value into the method. It would be helpful if you'd rename the parameter in your DisplayMemAddress
method to z
:
static unsafe void DisplayMemAddress(int z)
{
int* ptr = &z;
Console.WriteLine("0x" + new IntPtr(ptr).ToString("x"));
}
Now it's easier to talk about. You're displaying the address of z
, not x
or y
. That address will be on the stack (as an implementation detail) and as the stack is the same height in both calls, it'll show the same value. Now if you change the method to use pass-by-reference, you'll actually see the address of x
and y
:
class Program
{
static void Main(string[] args)
{
int x = 10; // int -> stack
int y = x; // assigning the value of num to mun.
DisplayMemAddress(ref x);
DisplayMemAddress(ref y);
Console.ReadLine();
}
static unsafe void DisplayMemAddress(ref int z)
{
fixed (int* ptr = &z)
{
Console.WriteLine("0x" + new IntPtr(ptr).ToString("x"));
}
}
}
To be honest, showing addresses isn't the best way of learning about reference types, value types and parameter passing IMO.
I have a couple of articles you might find useful though:
- Parameter passing
- Value types and reference types
精彩评论