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

โปรแกรม C สาธิตแนวคิด Strings ด้วย Pointers

ความหมายของ String ใน C

String ใน C คือ array ของ characters ที่จบด้วย null character ('\\0')

การประกาศและ Initialize String

1. ใช้ Character Constants

char string[10] = {'H', 'e', 'l', 'l', 'o', '\\0'};

2. ใช้ String Literal (แนะนำ)

char string[10] = "Hello"; // คอมไพเลอร์เติม \\0 ให้อัตโนมัติ

3. ใช้ Pointer ชี้ไปที่ String Literal

char *s = "Meghana"; // s ชี้ไปที่ string literal ใน read-only memory

คำเตือน: String literal ไม่ควรแก้ไขค่า (undefined behavior)

Arrays of Pointers to Strings

อาร์เรย์ที่แต่ละ element เป็น pointer ชี้ไปที่ string

char *a[] = {"one", "two", "three"};
  • a[0] ชี้ไปที่ "one"
  • a[1] ชี้ไปที่ "two"
  • a[2] ชี้ไปที่ "three"

ตัวอย่างโปรแกรมที่ 1: การเข้าถึง String ผ่าน Pointer

#include <stdio.h>
#include <string.h>
int main() {
    char *s = "Meghana";
    printf("%s\\n", s);      // Meghana (string ทั้งหมด)
    printf("%c\\n", *s);      // M (ตัวแรก)
    printf("%c\\n", *(s+4));  // a (ตัวที่ 5, index 4)
    printf("%c\\n", *s+5);    // R (ค่า ASCII ของ 'M' + 5 = 77+5=82 -> 'R')
    return 0;
}

ผลลัพธ์

Meghana
M
a
R

ตัวอย่างโปรแกรมที่ 2: Pointer Arithmetic กับ String

#include <stdio.h>
#include <string.h>
int main() {
    char *s = "Meghana";
    printf("%s\\n", s);       // Meghana
    printf("%c\\n", ++s+3);   // s ชี้ 'e' แล้ว +3 -> ชี้ 'a' แต่ %c พิมพ์ค่า garbage (เพราะเป็น address)
    printf("%c\\n", s+++3);   // post-increment: ใช้ค่าเก่าก่อน แล้วค่อย ++
    printf("%c\\n", *++s+3);  // pre-increment: ++s แล้ว dereference +3
    printf("%c\\n", *s+++3);  // dereference แล้ว post-increment pointer
    return 0;
}

ผลลัพธ์

Meghana
d
d
k
k

คำอธิบาย: ตัวอย่างนี้แสดง pointer arithmetic ที่ซับซ้อน ไม่แนะนำให้ใช้ในโค้ดจริง เพราะยากต่อการอ่านและบำรุงรักษา

แนวทางปฏิบัติที่ดี (Best Practices)

  • ใช้ const char * สำหรับ string literal: const char *s = "Hello";
  • ใช้ array ถ้าต้องการแก้ไข string: char s[] = "Hello";
  • ใช้ fgets แทน gets (unsafe)
  • หลีกเลี่ยง pointer arithmetic ที่ซับซ้อนบน string