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

สาธิตแนวคิดพอยน์เตอร์ (Pointers) โดยใช้ภาษา C


พอยน์เตอร์ (Pointer) คือตัวแปรที่จัดเก็บที่อยู่ของตัวแปรอีกตัวหนึ่ง

ไวยากรณ์สำหรับพอยน์เตอร์:

pointer = &variable;

ตัวอย่าง

โปรแกรม C สำหรับแนวคิดพอยน์เตอร์:

#include <stdio.h>

void main() {
    // ประกาศตัวแปรและพอยน์เตอร์ //
    int a = 2;
    int *p;
    
    // ประกาศความสัมพันธ์ระหว่างตัวแปรและพอยน์เตอร์ //
    p = &a;
    
    // พิมพ์คำสั่งตัวอย่างที่ต้องการ //
    printf("Size of the integer is %d\n", sizeof(int)); // 4
    printf("Address of %d is %d\n", a, p); // ค่าที่อยู่
    printf("Value of %d is %d\n", a, *p); // 2
    printf("Value of next address location of %d is %d\n", a, *(p+1)); // ค่าขยะจากที่อยู่ (p+1)
    printf("Address of next address location of %d is %d\n", a, (p+1)); // ค่าที่อยู่ +4
    
    // การแปลงชนิดพอยน์เตอร์ (Typecasting) //
    // ประกาศและกำหนดชนิดข้อมูลตัวอักษร //
    // a = 2 = 00000000 00000000 00000000 00000010 //
    char *p0;
    p0 = (char*)p;
    
    // พิมพ์คำสั่งที่ต้องการ //
    printf("Size of the character is %d\n", sizeof(char)); // 1
    printf("Address of %d is %d\n", a, p0); // ค่าที่อยู่ (p)
    printf("Value of %d is %d\n", a, *p0); // ไบต์แรกของค่า a = 2
    printf("Value of next address location of %d is %d\n", a, *(p0+1)); // ไบต์ที่สองของค่า a = 0
    printf("Address of next address location of %d is %d\n", a, (p0+1)); // ค่าที่อยู่ (p) + 1
}

ผลลัพธ์

เมื่อรันโปรแกรม จะได้ผลลัพธ์ดังนี้:

Size of the integer is 4
Address of 2 is 6422028
Value of 2 is 2
Value of next address location of 2 is 463824
Address of next address location of 2 is 6422032
Size of the character is 1
Address of 2 is 6422028
Value of 2 is 2
Value of next address location of 2 is 0
Address of next address location of 2 is 6422029