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

การเริ่มต้นอาร์เรย์หลายมิติ (Multidimensional Arrays) ใน C

อาร์เรย์หลายมิติ (Multi-dimensional arrays) คือ อาร์เรย์ของอาร์เรย์ ข้อมูลจัดเก็บในรูปแบบตาราง (Tabular) แบบ Row-major order (แถวต่อเนื่องในหน่วยความจำ)

ไวยากรณ์

type array_name[size1][size2]...[sizeN];

การเริ่มต้นค่า (Initialization)

type array_name[size1][size2]...[sizeN] = { 
    {elements_row1}, 
    {elements_row2}, 
    ..., 
    {elements_rowN} 
};

ตัวอย่าง: อาร์เรย์ 2 มิติ (2D Array)

#include <stdio.h>

int main() {
    // 2 แถว 3 คอลัมน์
    int arr[2][3] = { 
        {5, 2, 3},      // Row 0
        {28, 8, 30}     // Row 1
    };
    
    int i, j;
    
    // Nested loop เพื่อเข้าถึงทุกองค์ประกอบ
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 3; j++) {
            printf("arr[%d][%d] = %d\n", i, j, arr[i][j]);
        }
    }
    
    return 0;
}

ผลลัพธ์

arr[0][0] = 5
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 28
arr[1][1] = 8
arr[1][2] = 30

การจัดเก็บในหน่วยความจำ (Row-Major Order)

Memory Address:  LOW → HIGH
Index:           [0][0] [0][1] [0][2] [1][0] [1][1] [1][2]
Value:             5      2      3     28      8     30
Offset:            0      1      2      3      4      5  (× sizeof(int))

การคำนวณ Index แบบ Manual (1D Mapping)

// แทน arr[row][col] ใช้ arr[row * COLS + col]
#define ROWS 2
#define COLS 3
int arr[ROWS * COLS] = {5, 2, 3, 28, 8, 30};

// เข้าถึง arr[1][2] → arr[1 * 3 + 2] = arr[5] = 30

การเริ่มต้นค่าแบบไม่ครบ (Partial Initialization)

// ค่าที่ไม่ได้ระบุจะเป็น 0 อัตโนมัติ
int arr[3][4] = {
    {1, 2},        // Row 0: 1, 2, 0, 0
    {3},           // Row 1: 3, 0, 0, 0
    {}             // Row 2: 0, 0, 0, 0
};

การละขนาดมิติแรก (Omitting First Dimension)

// ได้เฉพาะมิติแรกเท่านั้น
int arr[][3] = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};  // Compiler คำนวณเป็น 3 rows อัตโนมัติ

อาร์เรย์ 3 มิติขึ้นไป

// 3 มิติ: 2 x 3 x 4
int arr[2][3][4] = {
    {  // Layer 0
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12}
    },
    {  // Layer 1
        {13, 14, 15, 16},
        {17, 18, 19, 20},
        {21, 22, 23, 24}
    }
};

Best Practices

  • ใช้ #define หรือ const สำหรับขนาดมิติ เพื่อความอ่านง่ายและปรับเปลี่ยนง่าย
  • หลีกเลี่ยงอาร์เรย์มิติสูงมาก (> 3D) - ควรใช้โครงสร้างข้อมูลอื่น
  • ใน C++ ควรใช้ std::vector<std::vector<T>> หรือ std::array แทน
  • ระวัง Stack Overflow กับอาร์เรย์ขนาดใหญ่ - ใช้ Dynamic Allocation แทน