ใน 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