2D Arrays
This is mostly useful for implementing matrices or tables of data. There are three methods for declaring a 2D array:
- Normal declaration
int A[3][4];
- An array of 3 * 4 size will be created inside the main memory, with three rows and four columns. The memory will be allocated like a single dimension array, but the compiler allows us to access it as a 2D array with the row number and column number, for example with
A[1][2] = 15; - We can also directly mention the list of elements
- This one is fully stack allocated.
int A[3][4] = {{1, 2, 3, 4}, {2, 4, 6, 8}, {3, 5, 7, 9}};
- With pointers
- Declaring an array of int pointers, and pointing them each to an array of size four, created in heap.
- Even with this structure, you can access it just like a normal array.
- This is partially in the heap, as
int *Ais created in the stack.
int *A[3];
A[0] = (int *)malloc(4 * sizeof(int));
A[1] = (int *)malloc(4 * sizeof(int));
A[2] = (int *)malloc(4 * sizeof(int));
A[1][2] = 15;
- With double pointers
- This one is fully heap allocated.
#include <stdlib.h>
int main() {
int **A;
A = (int **)malloc(3 * sizeof(int *));
A[0] = (int *)malloc(4 * sizeof(int));
A[1] = (int *)malloc(4 * sizeof(int));
A[2] = (int *)malloc(4 * sizeof(int));
// Accessing the 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
A[i][j] = 5;
}
}
}