c-sharp
  1. c-sharp-program-to-access-array-elements-using-pointer

Program to Access Array Elements Using Pointer - (C# Basic Programs)

In C#, we can use pointers to access the elements of an array. It allows us to manipulate the elements of an array directly in memory. In this tutorial, we'll be discussing a program to access array elements using pointers in C#.

Syntax

The syntax for accessing array elements using pointers in C# is as follows:

var arr = new int[] {1, 2, 3, 4, 5};
fixed (int* p = arr)
{
    for (int i = 0; i < arr.Length; i++)
    {
        Console.WriteLine(*(p + i));
    }
}

Example

using System;

class Program
{
    static unsafe void Main(string[] args)
    {
        int[] arr = { 1, 2, 3, 4, 5 };
        fixed (int* p = arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                Console.WriteLine(*(p + i));
            }
        }
    }
}

Output:

1
2
3
4
5

Explanation

In this program, we declare an integer array with the name arr. We then use the fixed keyword to pin the array in memory, which allows us to access its elements using pointers. We then declare an integer pointer with the name p and assign it the value of the address of the first element of the array. We use a for loop to iterate through the array and access its elements using the * operator along with the pointer p.

Use

Accessing array elements using pointers in C# can be useful in certain situations where we need to manipulate the elements of an array directly in memory. It can also help optimize performance in some cases since direct memory access is generally faster than accessing elements using array indices.

Summary

In this tutorial, we discussed a program to access array elements using pointers in C#. We covered the syntax, example, explanation, use, and benefits of using pointers to access array elements in C#. Accessing array elements using pointers can be a useful technique in certain programming scenarios, and understanding how to use it can help optimize C# programs for better performance.

Published on: