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