Pointer Declaration, Initialization, Accessing
1. Declaration
int *p; // p เป็น Pointer ชี้ไปที่ int
2. Initialization
int qty = 175;
int *p = &qty; // p เก็บ Address ของ qty
3. Accessing (Dereference)
printf("Value: %d\n", *p); // 175
*p = 200; // เปลี่ยนค่า qty ผ่าน p
printf("New qty: %d\n", qty); // 200
ภาพจำลองหน่วยความจำ
Variable: qty (int) Address: 0x7ffd1234 Value: 175 Pointer: p (int *) Address: 0x7ffd5678 Value: 0x7ffd1234 (Address of qty) *p → ไปที่ 0x7ffd1234 → อ่านค่า 175
ตัวอย่าง: Pointer Arithmetic กับ String
#include <stdio.h>
int main() {
char s[] = {'a', 'b', 'c', '\n', 'c', '\0'};
char *p, *str, *str1;
p = &s[3]; // p ชี้ที่ '\n' (index 3, ASCII 10)
str = p; // str ชี้ที่เดียวกับ p
str1 = s; // str1 ชี้ที่ 'a' (index 0, ASCII 97)
// ++*p: เพิ่มค่าที่ p ชี้ (\n=10 → 11)
// ++*str1: เพิ่มค่าที่ str1 ชี้ (a=97 → 98)
// ผลรวม - 32 = 11 + 98 - 32 = 77
printf("%d\n", ++*p + ++*str1 - 32);
return 0;
}
ผลลัพธ์: 77
อธิบายการคำนวณ
s[3] = '\n' (ASCII 10)
s[0] = 'a' (ASCII 97)
++*p → ++('\n') → 10+1 = 11
++*str1 → ++('a') → 97+1 = 98
11 + 98 - 32 = 77
Pointer Arithmetic พื้นฐาน
| Expression | Result | หมายเหตุ |
|---|---|---|
ptr + 1 | Address ถัดไป | + sizeof(type) ไบต์ |
ptr - 1 | Address ก่อนหน้า | - sizeof(type) ไบต์ |
ptr2 - ptr1 | จำนวน Elements ระหว่างกัน | Type ต้องเหมือนกัน |
ptr++ | Post-increment | ใช้ค่าก่อน เลื่อนทีหลัง |
++ptr | Pre-increment | เลื่อนก่อน ใช้ค่าทีหลัง |
Best Practices
- Initialize Pointer เสมอ (
NULLหรือ Address ที่ถูกต้อง) - Check
NULLก่อน Dereference - ใช้
constถ้าไม่ต้องการแก้ค่า:const int *p - หลีกเลี่ยง Pointer Arithmetic ที่ซับซ้อนเกินไป