Pointer เก็บ address ของตัวแปร 2D array จัดเก็บในหน่วยความจำแบบ row-major
Memory Layout ของ 2D Array
int a[3][3] = {1,2,3,4,5,6,7,8,9};
// Address base = 1234 (สมมติ)
// a[i][j] = *(base + i*cols + j) * scale_factor
โปรแกรม: ใช้ Pointer เข้าถึง 2D Array
#include <stdio.h>
main() {
int a[3][3], i, j;
int *p;
printf("Enter elements of 2D array:\n");
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
scanf("%d", &a[i][j]);
p = &a[0][0];
printf("Elements of 2D array:\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++)
printf("%d\t", *(p + i*3 + j));
printf("\n");
}
}
ผลลัพธ์
Enter elements of 2D array:
1 2 3
4 5 6
7 8 9
Elements of 2D array:
1 2 3
4 5 6
7 8 9