Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Pointer ใน C# คืออะไร

Pointer (ตัวชี้) ใน C#

Pointer คือตัวแปรที่เก็บ Address (ที่อยู่หน่วยความจำ) ของตัวแปรอีกตัวหนึ่ง ใช้ใน unsafe Context เท่านั้น

ไวยากรณ์


type* variableName;
// ตัวอย่าง
int* p;      // Pointer to int
double* d;   // Pointer to double

Operators หลัก

Operatorชื่อฟังก์ชัน
&Address-ofได้ Address ของตัวแปร
*Dereference / Indirectionเข้าถึงค่าที่ Address นั้น
->Member Accessเข้าถึง Member ผ่าน Pointer (struct)
[]Pointer IndexingPointer Arithmetic (ptr[i])

ตัวอย่าง: ประกาศและใช้ Pointer


using System;

class Program
{
    static unsafe void Main(string[] args)
    {
        int val = 50;
        int* ptr = &val; // ได้ Address ของ val
        
        Console.WriteLine($"Data: {val}");
        Console.WriteLine($"Address: {(int)ptr}"); // Cast เป็น int เพื่อแสดง
        Console.WriteLine($"Value via Pointer: {*ptr}"); // Dereference
        
        *ptr = 100; // เปลี่ยนค่าผ่าน Pointer
        Console.WriteLine($"New Value: {val}"); // 100
        
        Console.ReadKey();
    }
}

ผลลัพธ์


Data: 50
Address: 12345678 (ตัวอย่าง)
Value via Pointer: 50
New Value: 100

Pointer Arithmetic


unsafe void PointerArithmetic()
{
    int[] arr = { 10, 20, 30, 40, 50 };
    fixed (int* ptr = arr) // Pin Array
    {
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine($"ptr[{i}] = {ptr[i]}"); // *(ptr + i)
        }
        
        int* p = ptr;
        Console.WriteLine(*p);     // 10
        Console.WriteLine(*(p+1)); // 20
        p += 2;
        Console.WriteLine(*p);     // 30
    }
}

เมื่อไหร่ใช้ Pointer

  • P/Invoke (Call Native DLL)
  • Image Processing / Graphics (Pixel Manipulation)
  • High-performance Numerical Computing
  • Interop กับ Unmanaged Code

ทางเลือกปลอดภัยกว่า (Modern C#)

  • Span<T> / Memory<T> - Safe Pointer-like Access
  • stackalloc - Stack Allocation (ใน unsafe)
  • Unsafe.As<T>() - Type Reinterpretation