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

การเริ่มต้นอาร์เรย์ขนาดตัวแปร (Variable Length Arrays) ใน C

Variable Length Arrays (VLA) เป็นอาร์เรย์ที่ขนาดถูกกำหนดในขณะรันไทม์ (Runtime) แทนที่จะเป็นคอมไพล์ไทม์ (Compile-time) ฟีเจอร์นี้ถูกนำมารองรับในมาตรฐาน C99 (แต่เป็น Optional ใน C11 และถูกลบใน C23)

ตัวอย่างการใช้งาน VLA

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

int main() {
    int n;
    printf("Enter the size of the array: ");
    scanf("%d", &n);
    
    // VLA: ขนาดถูกกำหนดโดยตัวแปร n ในขณะรัน
    int arr[n];
    
    // เริ่มต้นค่าอาร์เรย์
    for(int i = 0; i < n; i++) {
        arr[i] = i + 1;
    }
    
    // แสดงผล
    printf("The array elements are: ");
    for(int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    
    return 0;
}

ผลลัพธ์ตัวอย่าง

Enter the size of the array: 10
The array elements are: 1 2 3 4 5 6 7 8 9 10

คำอธิบาย

  1. int n; - ประกาศตัวแปรกำหนดขนาด
  2. scanf("%d", &n); - รับขนาดจากผู้ใช้ในขณะรัน
  3. int arr[n]; - สร้าง VLA ขนาด n (จัดสรรบน Stack)
  4. ใช้ลูป for เริ่มต้นค่าและแสดงผล

ข้อดีและข้อเสีย

ข้อดีข้อเสีย
ยืดหยุ่น - ขนาดขึ้นกับ Inputจัดสรรบน Stack - อาจเกิด Stack Overflow หากขนาดใหญ่
ไม่ต้องใช้ malloc/freeไม่สามารถใช้ sizeof(arr) ได้ถูกต้องในบางกรณี
Syntax เรียบง่ายไม่รองรับใน C++ (GCC มี extension เท่านั้น)
Performance ดีกว่า malloc สำหรับขนาดเล็กถูกลบออกจากมาตรฐาน C23

ตัวเลือกแทน VLA (Alternatives)

1. Dynamic Allocation (malloc) - แนะนำสำหรับ Production

int *arr = malloc(n * sizeof(int));
if (arr == NULL) { /* handle error */ }
// ใช้งาน...
free(arr);

2. C++: std::vector

#include <vector>
std::vector<int> arr(n);  // ขนาดไดนามิก จัดการหน่วยความจำอัตโนมัติ

3. Fixed Maximum Size (ถ้าขนาดสูงสุดทราบล่วงหน้า)

#define MAX_SIZE 1000
int arr[MAX_SIZE];
int n;  // actual size <= MAX_SIZE

ข้อสังเกตสำคัญ

  • VLA ไม่ใช่บังคับใน C11/C18 (macro __STDC_NO_VLA__ จะถูกกำหนดถ้าไม่รองรับ)
  • Microsoft Visual C++ (MSVC) ไม่รองรับ VLA เลย
  • หลีกเลี่ยง VLA ขนาดใหญ่ (> 1MB) เพื่อป้องกัน Stack Overflow
  • ใน C++ ควรใช้ std::vector หรือ std::unique_ptr แทน