ตัวอย่างโปรแกรม C ใช้ Variable-Length Arrays (VLA) และ Dynamic Memory Allocation จำลองระบบห้องสมุดที่มีชั้นวางหนังสือหลายชั้น รองรับ 3 คำสั่ง:
- Command 1 (1, x, y): เพิ่มหนังสือที่มี y หน้า ที่ชั้น x
- Command 2 (2, x, y): แสดงจำนวนหน้าของหนังสือลำดับ y ที่ชั้น x
- Command 3 (3, x, 0): แสดงจำนวนหนังสือทั้งหมดที่ชั้น x
อัลกอริทึม
- สร้าง Array
b[s]เก็บจำนวนหนังสือแต่ละชั้น (size = จำนวนชั้น) - สร้าง Array of Pointers
p[s]แต่ละชี้ไปยัง Array เก็บจำนวนหน้าของหนังสือในชั้นนั้น - ใช้
realloc()ขยาย Memory เมื่อเพิ่มหนังสือใหม่ - คำสั่ง 2: พิมพ์
p[x][y]| คำสั่ง 3: พิมพ์b[x] - ปล่อย Memory ทั้งหมดเมื่อจบโปรแกรม
โค้ดโปรแกรม
#include <stdio.h>
#include <stdlib.h>
void solve(int s, int q, int q_array[][3]) {
int *b = (int*)malloc(sizeof(int) * s);
int **p = (int**)malloc(sizeof(int*) * s);
for (int i = 0; i < s; i++) {
b[i] = 0;
p[i] = (int*)malloc(sizeof(int)); // Initial allocation
}
for (int loopCount = 0; loopCount < q; loopCount++) {
int qtype = q_array[loopCount][0];
if (qtype == 1) { // Add book
int x = q_array[loopCount][1];
int y = q_array[loopCount][2];
b[x] += 1;
p[x] = realloc(p[x], b[x] * sizeof(int));
p[x][b[x] - 1] = y;
}
else if (qtype == 2) { // Query page count
int x = q_array[loopCount][1];
int y = q_array[loopCount][2];
printf("%d\n", p[x][y]);
}
else { // qtype == 3: Query book count
int x = q_array[loopCount][1];
printf("%d\n", b[x]);
}
}
// Free memory
if (b) free(b);
for (int i = 0; i < s; i++) {
if (p[i]) free(p[i]);
}
if (p) free(p);
}
int main() {
int input_arr[][3] = {{1, 3, 23}, {1, 4, 128}, {2, 3, 0}, {3, 4, 0}};
solve(4, 4, input_arr);
return 0;
}
Input
s = 4 shelves, q = 4 queries Commands: 1 3 23 // Add book 23 pages to shelf 3 1 4 128 // Add book 128 pages to shelf 4 2 3 0 // Query shelf 3, book 0 pages 3 4 0 // Query shelf 4, book count
Output
23 1
คำอธิบาย:
- คำสั่ง 1: เพิ่มหนังสือ 23 หน้า ที่ชั้น 3 → b[3]=1, p[3][0]=23
- คำสั่ง 2: เพิ่มหนังสือ 128 หน้า ที่ชั้น 4 → b[4]=1, p[4][0]=128
- คำสั่ง 3: Query p[3][0] → พิมพ์ 23
- คำสั่ง 4: Query b[4] → พิมพ์ 1
ข้อสังเกต: โค้ดใช้ 0-based indexing สำหรับชั้นและหนังสือ ต้องระวัง Bounds Checking ในระบบจริง