C Lesson 24 – 2D Arrays and Pointers | Dataplexa

2D Arrays and Pointers in C

You already understand arrays and pointers separately.

Now we combine them to understand one of the most important ideas in C: how multi-dimensional data lives in memory.

Do not rush this lesson. If you understand this, many advanced topics become easy.


What Is a 2D Array?

A 2D array is simply an array of arrays.

Think of it as a table with rows and columns.


int matrix[2][3];

This means:

  • 2 rows
  • 3 columns
  • Total elements = 6

Visual Understanding

Imagine this structure:

Row 0 → [ a  b  c ]
Row 1 → [ d  e  f ]

But in memory, all values are stored in a single continuous block.


Initializing a 2D Array


int matrix[2][3] = {
    {1, 2, 3},
    {4, 5, 6}
};

Each inner brace represents one row.


Accessing Elements


printf("%d", matrix[1][2]);

This accesses:

  • Row index 1
  • Column index 2

Indexes always start from 0.


2D Array and Memory Layout

Even though the array looks like a table, memory stores it linearly:

1  2  3  4  5  6

This is why pointers work smoothly with arrays.


Pointer to 2D Array

When passing a 2D array to a function, you must specify the column size.


void display(int (*arr)[3]) {
    printf("%d", arr[0][1]);
}

Here:

  • arr is a pointer
  • It points to an array of 3 integers

Accessing 2D Array Using Pointers

These two expressions are equivalent:


matrix[i][j]
*(*(matrix + i) + j)

The pointer version shows how memory navigation works.


Example Program


#include <stdio.h>

int main() {
    int matrix[2][3] = {
        {1, 2, 3},
        {4, 5, 6}
    };

    for(int i = 0; i < 2; i++) {
        for(int j = 0; j < 3; j++) {
            printf("%d ", *(*(matrix + i) + j));
        }
        printf("\n");
    }

    return 0;
}

Why This Matters

Understanding 2D arrays and pointers helps you with:

  • Matrix operations
  • Image processing
  • Game boards
  • Dynamic 2D memory

Mini Practice

  • Create a 2×2 matrix
  • Store values
  • Print using pointer notation

Quick Quiz

Q1. Is a 2D array stored as a table in memory?

No, it is stored linearly.

Q2. What does matrix[i][j] represent?

Element at row i, column j.

Q3. Why must column size be specified?

To calculate memory offsets correctly.

Q4. Are pointer and array access equivalent?

Yes.

Q5. Is this concept important for dynamic matrices?

Yes, very important.