简体   繁体   中英

Confused about pointers in C#

I know this may be a low quality question but please dont -rep me because I am very confused about this as a beginner to pointers and I can't find an answer to my question anywhere...

using System;

class MyTest
{
    unsafe static void Swap( int *a, int *b )
    {
        int tmp = *a;

        *a = *b;
        *b = tmp;
    }

    unsafe static void Main(string [] args)
    {
        int x = 5;
        int y = 12;

        Console.WriteLine( "x = {0}, y = {1}", x, y );

        Swap( &x, &y );

        Console.WriteLine( "x = {0}, y = {1}", x, y );
    }
}

I am really confused about this....Sometimes they do *ptr=&address which assigns the ADDRESS which is a hexadecimal value to a pointer....so THAT is pointing the pointer to an ADDRESS which is asigning the pointer a hexadecimal value...

other times they do *ptr=85; which is basically asigning the pointee an integer value of 85 so *ptr holds the value 85 and doing *ptr accesses the pointer's value where as int ptr is the ADDRESS of the pointer so it doesnt make sense to me how they SWAP the addresses of the pointers when all I see them doing is swapping the VALUES by using *ptr...

Please clear my confusion

I think you've just about got it. It isn't the addresses of the pointers which are being swapped, but rather it is the values that get swapped, because you send the address of the pointers to the Swap() function. When you call Swap(&x,&y) , an address pointer to x and an address pointer to y are sent to the function, and Swap() can use those addresses to know where to put the new values of the swap.

In other words, when you pass pointers, you're passing a memory location that you will be using values from, not simply the values themselves. In this way, your function can update the original variables. This is the beauty (and the curse) of languages that use pointers.

As to your comment about *ptr = &address , this is only valid if ptr is a pointer to a pointer, which is a bit more advanced. Whenever you assign a value with the * operator, you're assigning the value of that pointer to the value on the right side of the equals sign. If the pointer happens to point to another pointer, it can be an address.

I have not used pointers in C# but as per my knowledge in C

to assign an address to a pointer, syntax was

ptr=&address

and not

*ptr=&address

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