如何在 C# 中使用指標訪問陣列元素?


在 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)

         /* let us have array address in pointer */
         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

更新於:03-04-2020

超過 3K 的瀏覽量

開啟你的 職業生涯

完成課程以獲得認證

開始學習
廣告
© . All rights reserved.