ความหมาย
Two-dimensional array (2D array) ใช้เก็บข้อมูลแบบตาราง (rows x columns) เหมาะสำหรับ matrix, spreadsheet, game board
Syntax
datatype array_name[row_size][col_size];
ตัวอย่าง: int a[5][5]; // 5 rows, 5 columns = 25 elements
การจัดเก็บในหน่วยความจำ (Row-major)
Row 0: a[0][0], a[0][1], a[0][2]...
Row 1: a[1][0], a[1][1], a[1][2]...
| a[0][0] 10 | a[0][1] 20 | a[0][2] 30 |
| a[1][0] 40 | a[1][1] 50 | a[1][2] 60 |
| a[2][0] | a[2][1] | a[2][2] |
Initialization
Compile-time
int a[3][3] = {10,20,30,40,50,60,70,80,90};
// หรือ
int a[3][3] = {{10,20,30}, {40,50,60}, {70,80,90}};Runtime
int a[3][3], i, j;
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
scanf("%d", &a[i][j]);ตัวอย่างโปรแกรมที่ 1: Compile-time Init
#include <stdio.h>
int main() {
int a[3][3] = {10,20,30,40,50,60,70,80,90};
int i, j;
printf("Elements:\\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++)
printf("%d\\t", a[i][j]);
printf("\\n");
}
return 0;
}ผลลัพธ์
Elements: 10 20 30 40 50 60 70 80 90
ตัวอย่างโปรแกรมที่ 2: Runtime Init
#include <stdio.h>
int main() {
int a[3][3], i, j;
printf("ป้อน elements:\\n");
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
scanf("%d", &a[i][j]);
printf("Elements:\\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++)
printf("%d\\t", a[i][j]);
printf("\\n");
}
return 0;
}ผลลัพธ์
ป้อน elements: 1 2 3 4 5 6 7 8 9 Elements: 1 2 3 4 5 6 7 8 9
ตัวอย่างโปรแกรมที่ 3: Matrix Operations (Sum & Product)
#include <stdio.h>
int main() {
int A[2][3], B[2][3], sum[2][3], product[2][3];
int i, j;
printf("Matrix A:\\n");
for (i = 0; i < 2; i++)
for (j = 0; j < 3; j++) {
printf("A[%d][%d]: ", i, j);
scanf("%d", &A[i][j]);
}
printf("Matrix B:\\n");
for (i = 0; i < 2; i++)
for (j = 0; j < 3; j++) {
printf("B[%d][%d]: ", i, j);
scanf("%d", &B[i][j]);
}
printf("Sum (A+B):\\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
sum[i][j] = A[i][j] + B[i][j];
printf("%d\\t", sum[i][j]);
}
printf("\\n");
}
printf("Product (A*B element-wise):\\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
product[i][j] = A[i][j] * B[i][j];
printf("%d\\t", product[i][j]);
}
printf("\\n");
}
return 0;
}ผลลัพธ์ตัวอย่าง
Matrix A: A[0][0]: 2 A[0][1]: 3 A[0][2]: 1 A[1][0]: 2 A[1][1]: 4 A[1][2]: 5 Matrix B: B[0][0]: 1 B[0][1]: 2 B[0][2]: 3 B[1][0]: 5 B[1][1]: 6 B[1][2]: 7 Sum (A+B): 3 5 4 7 10 12 Product (A*B element-wise): 2 6 3 10 24 35
ข้อควรระวัง
- 2D array บน stack มีขีดจำกัดขนาด (ประมาณ 1-8 MB)
- Array ใหญ่ควรใช้ malloc:
int **p = malloc(rows * sizeof(int*)); for(i) p[i] = malloc(cols * sizeof(int)); - ส่ง 2D array ให้ฟังก์ชัน ต้องระบุ column size:
void func(int arr[][3], int rows)