Accessing Array Elements Using a Pointer
suggest changeIn C#, an array and a pointer to the same element type are not the same type. For example, int* p and int[] p are not the same type. You can increment the pointer p because it is not fixed in memory, but an array’s address is fixed, so you cannot increment the array.
To access array elements through a pointer, as you traditionally do in C or C++, pin the array with the fixed statement.
The following example demonstrates this:
using System;
namespace UnsafeCodeApplication
{
class TestPointer
{
public unsafe static void Main()
{
int[] list = {10, 100, 200};
fixed(int *ptr = list)
/* let us have array address in pointer */
for ( int i = 0; i < 3; i++)
{
Console.WriteLine("Address of list[{0}]={1}",i,(int)(ptr + i));
Console.WriteLine("Value of list[{0}]={1}", i, *(ptr + i));
}
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result. The address values assume a 32-bit process; the cast of the pointer to int truncates a 64-bit address.
Address of list[0]=31627168
Value of list[0]=10
Address of list[1]=31627172
Value of list[1]=100
Address of list[2]=31627176
Value of list[2]=200
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents