Use Pointer in C #

Source: Internet
Author: User

I think many c Program The reason why the programmer is unwilling to learn Java is that Java does not support pointers, but now C #, similar to Java, supports pointers. You can use the unsafe keyword to tell the compiler the following functions or Code Is not safe. Once you use unsafe, you can use pointers in the unsafe area.

Procedure 1
Using system;
Class Nish
{
Unsafe static void increment (int * P)
{
// Increment the int pointed to by P
* P = * p + 1;
}
Public static void main ()
{
Int I = 1;
// We pass the address of the int to the function as it expects a pointer
Unsafe increment (& I );
// Now we print out the value of I
Console. writeline (I );
}
}

When you run this program, you will see output result 2. This is because you have sent the address of variable I to the Increment Function for processing. Variable I is created in the stack, and & I indicates its address in the stack. In this way, in the increment function, P points to the address of I. When we add 1 to * P, we actually add variable I.

Procedure 2
The following program will give you a clearer understanding:

Using system;
Class Nish
{
Unsafe public static int main ()
{
Int J = 100;
Int K = 100;
Console. writeline ("Address of J = {0} and address of K = {1}", (INT) & J, (INT) & K );
Console. writeline ("J = {0} k = {1}", j, k );
Int * P;
P = & J;
Console. writeline ("P now points to {0}", (INT) P );
* P = 200;
Console. writeline ("J = {0} k = {1}", j, k );
P = & K;
Console. writeline ("P now points to {0}", (INT) P );
* P = 300;
Console. writeline ("J = {0} k = {1}", j, k );

Return 0;
}
}

When running the above program, we will get the following results. You will see something you are familiar with. The following output results will clearly show the Program Execution Process:

Address of J = 1244312 and address of K = 1244308
J = 100 k = 100
P now points to 1244312
J = 200 k = 100
P now points to 1244308
J = 200 k = 300

First, assign the J address of the variable to P, so that when we change * P, the J value will also change automatically. Then we point P to the address of the variable k, and * P is changing K.

The Variable P also has its own address. The following program will clearly tell you everything.

Procedure 3
Using system;
Class Nish
{
Public static void main ()
{
Unsafe
{
Int A = 100;
Int * P;
P = &;
Console. writeline ("address of a is {0}", (INT) & );
Console. writeline ("P now points to {0}", (INT) P );
Console. writeline ("Address of the pointer Variable P is {0}", (INT) & P );
}
}
}

Run the above code and we will get the output shown below. You will also get some similar output. Note the use of the unsafe keyword here.

Address of A is 1244312
P now points to 1244312
Address of the pointer Variable P is 1244308

1244308 is the address of the pointer Variable P, and 1244312 is the address pointed to by the pointer P. We use * P to obtain the address.

Procedure 4
Okey. In the last program, I will introduce how to use pointers to operate strings. There is a program in this program to perform the encoding and decoding of a string through the exclusive or operation. If you send a string to this function, the string will be encoded. If you send an encoded string to this function, the string will be decoded. When this is not a secure encryption method, I just want to use this example to demonstrate the role of the pointer.

Using system;
Class Nish
{
Public static void main ()
{
String S = "Code project is cool ";
Console. Write ("the original string :");
Console. writeline ("{0} \ r \ n", S );

Char [] B = new char [100];
S. copyto (0, B, 0, 20 );

Console. Write ("the encoded string :");
Unsafe fixed (char * P = B) nencodedecode (P );
For (int t = 0; t <20; t ++)
Console. Write (B [T]);
Console. writeline ("\ r \ n ");

Console. Write ("the decoded string :");
Unsafe fixed (char * P = B) nencodedecode (P );
For (int t = 0; t <20; t ++)
Console. Write (B [T]);
Console. writeline ();

}
Unsafe public static void nencodedecode (char * s)
{
Int W;
For (INT y = 0; y <20; y ++)
{
W = (INT) * (S + y );
W = w ^ 5;
* (S + y) = (char) W;
}
}


The following is my output. You can also get it:

The original string: Code project is cool

The encoded string: fja '% uwjo' FQ % LV % fjji

The decoded string: Code project is cool

In this example, you will find a new keyword-fixed. When you use fixed before a statement or function, you are telling the. NET platform's garbage collector that the memory space occupied by the statement or function cannot be recycled before execution. Fixed keywords can only be used in insecure code. In this example, if the fixed keyword is not used, the execution result of this program is unpredictable, because the Garbage Collector will continuously recycle the memory space occupied by the controllable code. Fortunately, the compiler does not allow you to point to controllable variables unless you use the fixed keyword.

In this function, you can see that I use the * (S + Y) expression. S is the string address (note that it is the first address ). Y increases from 0 to 19 through loops. In this way, the * (s) address is 1000, * (S + 1) is 1002, * (S + 2) is 1004, and so on. The compiler knows that I am pointing to a character data, so it moves two bytes forward for the first time, because Char is 16 bits (which is different from C, in C, char only occupies 8 digits ).

Conclusion
When using unsafe code, you must be very careful. Any small errors, or even type errors, will cause the output results to be unknown, and such errors are hard to be detected by debugging. Of course, if you are a C/C ++ programmer and you have a thorough understanding of pointers, then I did not say anything. Good luck.
(Compilation: http://www.aspcn.com flying knife)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.