พอยน์เตอร์ (Pointer) คือตัวแปรที่จัดเก็บที่อยู่ของตัวแปรอีกตัวหนึ่ง
ไวยากรณ์สำหรับพอยน์เตอร์:
pointer = &variable;
ประเภทของพอยน์เตอร์ (Types of Pointers)
มีพอยน์เตอร์ 8 ประเภท ดังนี้:
Null Pointer
Void Pointer
Wild Pointer
Dangling Pointer
Complex Pointer
Near Pointer
Far Pointer
Huge Pointer
Null Pointer
สร้าง Null Pointer โดยกำหนดค่า NULL ตอนประกาศ ใช้เมื่อไม่ได้กำหนดที่อยู่ให้พอยน์เตอร์ Null Pointer จะมีค่า 0 เสมอ
ตัวอย่าง
โปรแกรม C สำหรับ Null Pointer:
#include <stdio.h>
int main() {
int *ptr = NULL; // null pointer
printf("The value inside variable ptr is:\n%d", ptr);
return 0;
}ผลลัพธ์
เมื่อรันโปรแกรม จะได้ผลลัพธ์ดังนี้:
The value inside variable ptr is: 0
Void Pointer
เป็นพอยน์เตอร์ที่ไม่มีชนิดข้อมูลเกี่ยวข้อง Void Pointer จัดเก็บที่อยู่ของชนิดใดก็ได้ และแปลงชนิดได้ทุกประเภท เรียกอีกอย่างว่า Generic Pointer ไม่มีชนิดข้อมูลมาตรฐาน สร้างด้วยคีย์เวิร์ด void
ตัวอย่าง
โปรแกรม C สำหรับ Void Pointer:
#include <stdio.h>
int main() {
void *p = NULL; // void pointer
printf("The size of pointer is:%d\n", sizeof(p)); // ขนาด p ขึ้นอยู่กับคอมไพเลอร์
return 0;
}ผลลัพธ์
เมื่อรันโปรแกรม จะได้ผลลัพธ์ดังนี้:
The size of pointer is: 8
Wild Pointer
Wild Pointers เรียกอีกอย่างว่า Uninitialized Pointers เพราะชี้ไปตำแหน่งหน่วยความจำสุ่ม อาจทำให้โปรแกรมล้มหรือทำงานผิดปกติ ไม่ควรใช้งาน ต้องระวังเมื่อทำงานกับ Wild Pointer
ตัวอย่าง
โปรแกรม C สำหรับ Wild Pointer:
#include <stdio.h>
int main() {
int *p; // wild pointer
printf("\n%d", *p);
return 0;
}
// Process returned -1073741819 (0xC0000005) execution time: 1.206 s
// Press any key to continue - ไม่ได้ผลลัพธ์ บางคอมไพเลอร์แสดงข้อผิดพลาด