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

อาร์เรย์หลายมิติใน C / C++


ใน C/C++ อาร์เรย์หลายมิติถูกกำหนดด้วยคำง่ายๆ ว่าเป็นอาร์เรย์ของอาร์เรย์ ในอาร์เรย์หลายมิติข้อมูลจะถูกจัดเก็บในรูปแบบตาราง (ในลำดับหลักแถว) ไดอะแกรมต่อไปนี้แสดงกลยุทธ์การจัดสรรหน่วยความจำสำหรับอาร์เรย์หลายมิติที่มีขนาด 3 x 3 x 3

อาร์เรย์หลายมิติใน C / C++

อัลกอริทึม

Begin
   Declare dimension of the array.
   Dynamic allocate 2D array a[][] using new.
   Fill the array with the elements.
   Print the array.
   Clear the memory by deleting it.
End

โค้ดตัวอย่าง

#include <iostream>
using namespace std;
int main() {
   int B = 4;
   int A = 5;
   int** a = new int*[B];
   for(int i = 0; i < B; ++i)
      a[i] = new int[A];
   for(int i = 0; i < B; ++i)
      for(int j = 0; j < A; ++j)
          a[i][j] = i;
   for(int i = 0; i < B; ++i)
      for(int j = 0; j < A; ++j)
         cout << a[i][j] << "\n";
   for(int i = 0; i < A; ++i)
      delete [] a[i];
      delete [] a;
   return 0;
}

ผลลัพธ์

0
0
0
0
0
1
1
1
1
1
2
2
2
2
2
3
3
3
3
3