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

การสร้าง Pointer สำหรับ Strings (Array of Pointers to Strings) ใน C

Array of Pointers to Strings** คือ อาร์เรย์ที่แต่ละสมาชิกเป็น Pointer ชี้ไปที่ตัวอักษรแรกของสตริง วิธีนี้ยืดหยุ่นและประหยัดหน่วยความจำกว่าอาร์เรย์ 2 มิติ

การประกาศและเริ่มต้นค่า

char *names[3] = {"one", "two", "three"};

// names[0] ชี้ไป "one"
// names[1] ชี้ไป "two"
// names[2] ชี้ไป "three"

ข้อดี gegenüber 2D Char Array

ลักษณะchar arr[][10]char *arr[]
หน่วยความจำคงที่ (ทุกแถวเท่ากัน)ตามความยาวสตริงจริง
ความยาวสตริงจำกัดโดย Column sizeไม่จำกัด
การสลับสตริงต้อง Copy ทีละตัวอักษรสลับ Pointer ได้เลย (เร็ว)
การแก้ไขสตริงได้ (ถ้าไม่ใช่ string literal)ได้ (ถ้าไม่ใช่ string literal)

ตัวอย่างที่ 1: แสดงชื่อนักศึกษา

#include <stdio.h>

int main() {
    char *students[] = {"Bhanu", "Ramu", "Hari", "Pinky"};
    int n = sizeof(students) / sizeof(students[0]);
    
    printf("Student List:\n");
    for(int i = 0; i < n; i++)
        printf("%d. %s\n", i+1, students[i]);
    
    return 0;
}

ผลลัพธ์

Student List:
1. Bhanu
2. Ramu
3. Hari
4. Pinky

ตัวอย่างที่ 2: รับสตริงจากผู้ใช้ (Dynamic)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_STUDENTS 10
#define MAX_LEN 50

int main() {
    char *students[MAX_STUDENTS];
    int count = 0;
    char buffer[MAX_LEN];
    
    printf("Enter names (empty to stop):\n");
    while(count < MAX_STUDENTS) {
        printf("%d: ", count + 1);
        if(!fgets(buffer, MAX_LEN, stdin)) break;
        
        buffer[strcspn(buffer, "\n")] = '\0';  // ลบ newline
        if(strlen(buffer) == 0) break;
        
        // จองหน่วยความจำและคัดลอก
        students[count] = malloc(strlen(buffer) + 1);
        strcpy(students[count], buffer);
        count++;
    }
    
    printf("\nEntered names:\n");
    for(int i = 0; i < count; i++) {
        printf("%d. %s\n", i+1, students[i]);
        free(students[i]);  // คืนหน่วยความจำ
    }
    
    return 0;
}

ตัวอย่างที่ 3: เรียงลำดับสตริง (Sort Strings)

#include <stdio.h>
#include <string.h>

int main() {
    char *fruits[] = {"banana", "apple", "orange", "mango", "grape"};
    int n = 5;
    char *temp;
    
    // Bubble Sort สลับ Pointer
    for(int i = 0; i < n-1; i++) {
        for(int j = 0; j < n-1-i; j++) {
            if(strcmp(fruits[j], fruits[j+1]) > 0) {
                temp = fruits[j];
                fruits[j] = fruits[j+1];
                fruits[j+1] = temp;
            }
        }
    }
    
    printf("Sorted:\n");
    for(int i = 0; i < n; i++)
        printf("%s\n", fruits[i]);
    
    return 0;
}

ผลลัพธ์

Sorted:
apple
banana
grape
mango
orange

สรุป

  • ใช้ char *arr[] สำหรับเก็บสตริงหลายๆ ตัวที่ความยาวไม่เท่ากัน
  • สตริง Literal อยู่ใน Read-only Memory → อย่าพยายามแก้ไข
  • ถ้าต้องแก้ไข ให้ malloc + strcpy แล้ว free ทีหลัง
  • เหมาะสำหรับ: เมนู, รายการชื่อ, คำสั่ง CLI, Dictionary