如何在 C# 中使用指针访问数组元素?

csharpprogrammingserver side programming

在 C# 中,数组名称和指向与数组数据相同的数据类型的指针不是同一变量类型。例如,int *p 和 int[] p 不是同一类型。您可以增加指针变量 p,因为它在内存中不固定,但数组地址在内存中是固定的,您不能增加它。

以下是示例 −

示例

using System;

namespace UnsafeCodeApplication {
   class TestPointer {
      public unsafe static void Main() {
          int[] list = {5, 25};
          fixed(int *ptr = list)

         /* 让我们在指针中拥有数组地址 */
         for ( int i = 0; i < 2; i++) {
            Console.WriteLine("Address of list[{0}]={1}",i,(int)(ptr + i));
            Console.WriteLine("Value of list[{0}]={1}", i, *(ptr + i));
         }
         Console.ReadKey();
      }
   }
}

输出

这是输出 −

Address of list[0] = 31627168
Value of list[0] = 5
Address of list[1] = 31627172
Value of list[1] = 25

相关文章