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

วิธีประกาศ 2D array แบบ dynamic ด้วย new ใน C++


2D array แบบ dynamic = array of pointers to arrays ต้อง allocate 2 ขั้นตอน:

  1. Allocate array ของ pointers (int**)
  2. Loop allocate แต่ละ row (1D array)

ตัวอย่าง

#include <iostream>
using namespace std;

int main() {
    int rows = 3, cols = 4;
    int** arr = new int*[rows];      // array ของ pointers
    for (int i = 0; i < rows; ++i)
        arr[i] = new int[cols];      // แต่ละ row
    // ใช้งาน arr[i][j] ได้ปกติ
    // ลบ memory: ลบ rows ก่อน แล้วค่อยลบ arr
    for (int i = 0; i < rows; ++i)
        delete[] arr[i];
    delete[] arr;
    return 0;
}

สำคัญ: ต้อง delete ในลำดับย้อนกลับ: delete[] arr[i] ทุก row ก่อน แล้ว delete[] arr ไม่งั้น memory leak