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

Pointer Operations และ ปัญหาของ Pointer ในภาษา C

Pointer = ตัวแปรเก็บ address ของตัวแปรอื่น

Pointer Operations

  1. Assignment - p = &var; กำหนด address
  2. Dereferencing - *p เข้าถึงค่าที่ address
  3. Pointer address - &p address ของ pointer เอง
  4. Pointer + int - p + n เลื่อน n elements (ขึ้นกับ sizeof type)
  5. Increment - p++ ชี้ element ถัดไป
  6. Pointer - int - p - n เลื่อนย้อนกลับ
  7. Decrement - p-- ชี้ element ก่อนหน้า
  8. Subtraction - p2 - p1 หาระยะห่าง (จำนวน elements)
  9. 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