C# program to access array elements using the pointer

Here, we are going to learn how to access array elements using the pointer in C#?
Submitted by Nidhi, on November 01, 2020

Here, we will access array elements using pointers. To use pointer we need to write unsafe code, to compile unsafe code we need to allow unsafe code by clicking on properties in solution explorer and then "Allow Unsafe Code" from the Build tab.

Program:

The source code to access array elements using pointers is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to access array elements using the pointer.

using System;

class UnsafeEx
{
    static unsafe void Main(string[] args)
    {
        int loop = 0;
        int[] intArr = { 10, 20, 30, 40, 50 };

        Console.WriteLine("Array elements are:");
        fixed (int* ptr = intArr)
        for (loop = 0; loop < intArr.Length; loop++)
        {
            Console.Write(*(ptr + loop)+" ");
        }
        Console.WriteLine();
    }
}

Output:

Array elements are:
10 20 30 40 50
Press any key to continue . . .

Explanation:

In the above program, we created class UnsafeEx that contains the Main() method, here we used the unsafe keyword with the Main() method to define the unsafe method that can use pointers.

In the Main() method, we created an array of integer elements then we assign the address of the array to the pointer and then print array elements using the pointer on the console screen.

C# Basic Programs »


ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.