How to access elements of an array using pointer notation in C#?


Usage of pointers in C# require the unsafe modifier. Also array elements can be accessed using pointers using the fixed keyword. This is because the array and the pointer data type are not the same. For example: The data type int[] is not the same as int*.

A program that demonstrates accessing array elements using pointers is given as follows.

Example

using System;
namespace PointerDemo {
   class Example {
      public unsafe static void Main() {
         int[] array = {55, 23, 90, 76, 9, 57, 18, 89, 23, 5};
         int n = array.Length;
         fixed(int *ptr = array)
         for ( int i = 0; i < n; i++) {
            Console.WriteLine("array[{0}] = {1}", i, *(ptr + i));
         }
      }
   }
}

Output

The output of the above program is as follows.

array[0] = 55
array[1] = 23
array[2] = 90
array[3] = 76
array[4] = 9
array[5] = 57
array[6] = 18
array[7] = 89
array[8] = 23
array[9] = 5

Now let us understand the above program.

The array contains 10 values of type int. The pointer ptr points to the start of the array using the fixed keyword. Then all the array values are displayed using for loop. The code snippet for this is given as follows −

int[] array = {55, 23, 90, 76, 9, 57, 18, 89, 23, 5};
int n = array.Length;
fixed(int *ptr = array)
for ( int i = 0; i < n; i++) {
   Console.WriteLine("array[{0}] = {1}", i, *(ptr + i));
}

Updated on: 26-Jun-2020

532 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements