29.12. Pointer arithmetic

You can perform pointer arithmetic in an unsafe context. Let's discuss the + and – binary operators when applied to pointers.

Adding a number n to a pointer will increment it by (n*y), where y is the size of the pointer's referent type in number of bytes. For example, if you are dealing with double pointers, adding 3 to the pointer will increase its value by 24 since the double type takes up eight bytes of space.

Study the example below:

 1: using System; 2: 3: public class TestClass{ 4: 5: public unsafe static void Main(){ 6: int a = 100; 7: int b = 101; 8: int c = 102; 9: int d = 103; 10: 11: Console.WriteLine("Addr of a :"+(int)&a); 12: Console.WriteLine("Addr of b :"+(int)&b); 13: Console.WriteLine("Addr of c :"+(int)&c); ...

Get From Java to C#: A Developer's Guide now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.