Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
Ankith Reddy

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));
         }
      }
   }
}

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));
}

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.