Pointer = ตัวแปรเก็บ address ของตัวแปรอื่น
Pointer Operations
- Assignment -
p = &var;กำหนด address - Dereferencing -
*pเข้าถึงค่าที่ address - Pointer address -
&paddress ของ pointer เอง - Pointer + int -
p + nเลื่อน n elements (ขึ้นกับ sizeof type) - Increment -
p++ชี้ element ถัดไป - Pointer - int -
p - nเลื่อนย้อนกลับ - Decrement -
p--ชี้ element ก่อนหน้า - Subtraction -
p2 - p1หาระยะห่าง (จำนวน elements) - Comparison -
p1 == p2, p1 < p2เปรียบเทียบ address
โปรแกรมสาธิต
#include <stdio.h>
main() {
int x = 10, y;
int *p = &x;
y = *p;
printf("x = %d\n", x);
printf("&x = %p\n", (void*)&x);
printf("*p = %d\n", *p);
printf("p = %p\n", (void*)p);
printf("y = %d\n", y);
*p = 25;
printf("now x = %d\n", x);
}
ผลลัพธ์
x = 10
&x = 0x7ffc...
*p = 10
p = 0x7ffc...
y = 10
now x = 25