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

ตัวอย่างการใช้ Pointer ในภาษา C (พื้นฐานถึง Type Casting)


Pointer คือตัวแปรที่เก็บที่อยู่ (Address) ของตัวแปรอื่น

คุณสมบัติ Pointer

  • ประหยัดหน่วยความจำ
  • เข้าถึงหน่วยความจำโดยตรง เร็วกว่า
  • จัดสรร/ปล่อยหน่วยความจำไดนามิกได้
  • ใช้ร่วมกับ Data Structures

การประกาศและใช้งาน

int *p;           // ประกาศ pointer ชี้ int
int qty = 175;
p = &qty;         // p เก็บ address ของ qty
printf("%d", *p); // *p = dereference = ค่าของ qty (175)

ตัวอย่างการใช้ Pointer ในภาษา C (พื้นฐานถึง Type Casting)

โปรแกรมสาธิตครบ: Address, Value, Pointer Arithmetic, Type Casting

#include <stdio.h>
int main() {
    int a = 2;
    int *p = &a;
    
    printf("Size of int: %d\n", sizeof(int));           // 4
    printf("Address of a: %p\n", (void*)p);              // address
    printf("Value at p: %d\n", *p);                      // 2
    printf("Value at p+1: %d\n", *(p+1));                // garbage
    printf("Address p+1: %p\n", (void*)(p+1));           // address + 4
    
    // Type casting: int* -> char* (ดู byte ต่อ byte)
    char *p0 = (char*)p;
    printf("\n--- char* view ---\n");
    printf("Size of char: %d\n", sizeof(char));          // 1
    printf("Address: %p\n", (void*)p0);
    printf("Byte 0: %d\n", *p0);        // 2 (LSB)
    printf("Byte 1: %d\n", *(p0+1));    // 0
    printf("Address+1: %p\n", (void*)(p0+1));           // address + 1
    
    return 0;
}

ผลลัพธ์

Size of int: 4
Address of a: 0x6422028
Value at p: 2
Value at p+1: 10818512 (garbage)
Address p+1: 0x6422032
Size of char: 1
Address: 0x6422028
Byte 0: 2
Byte 1: 0
Address+1: 0x6422029