2D array จัดสรร dynamically ใน C ได้ด้วย single pointer หมายถึง memory block ขนาด row*column*dataTypeSize จัดสรรด้วย malloc และ pointer arithmetic ใช้เข้าถึง matrix elements
โปรแกรมสาธิต:
ตัวอย่าง
#include <stdio.h> #include <stdlib.h> int main() { int row = 2, col = 3; int *arr = (int *)malloc(row * col * sizeof(int)); int i, j; for (i = 0; i < row; i++) for (j = 0; j < col; j++) *(arr + i*col + j) = i + j; printf("The matrix elements are:\n"); for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { printf("%d ", *(arr + i*col + j)); } printf("\n"); } free(arr); return 0; } The output of the above program is as follows.
The matrix elements are: 0 1 2 1 2 3
เข้าใจโปรแกรมข้างต้น:
2-D array arr จัดสรร dynamically ด้วย malloc เริ่มต้น 2-D array ด้วย nested for loop และ pointer arithmetic Code snippet:
int row = 2, col = 3; int *arr = (int *)malloc(row * col * sizeof(int)); int i, j; for (i = 0; i < row; i++) for (j = 0; j < col; j++) *(arr + i*col + j) = i + j;
แสดงค่า 2-D array แล้ว free memory ด้วย free Code snippet:
printf("The matrix elements are:\n"); for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { printf("%d ", *(arr + i*col + j)); } printf("\n"); } free(arr);