Course contentsShow
← C
Lesson 408 of 1,2196. Arrays and StringsFree lesson

Memory layout: Row-major order

Memory layout: Row-major order

What you'll learn: Understand how C flattens multi-dimensional arrays into a single, continuous line of memory addresses.

The Illusion of the Grid

When we declare a 2D array like int grid[2][3], our brains immediately visualize a table with two rows and three columns. We imagine the data sitting in a neat square. However, computer memory (RAM) is not a grid; it is a long, one-dimensional street of numbered mailboxes.

To bridge this gap, C uses a system called row-major order. This means the computer stores the array row by row. It places the entire first row in memory, followed immediately by the entire second row, and so on.

Visualizing the Sequence

Imagine you have a small grid representing a tiny image:

int photo[2][3] = {
    {10, 20, 30}, // Row 0
    {40, 50, 60}  // Row 1
};

In your mind, 10 is above 40. But in the computer's memory, the elements are laid out in a straight line like this:

[10][20][30][40][50][60]

If you were to look at the memory addresses, you would see that photo[0][2] (the end of the first row) is sitting right next to photo[1][0] (the start of the second row). There are no gaps or "line breaks" in your RAM.

Why This Matters

Knowing that C uses row-major order explains why the computer needs to know the size of the columns. When you ask for photo[1][0], the computer calculates the location by saying: "I need to skip exactly one full row of three elements to get to the start of the second row."

If you imagine walking through a building, row-major order is like walking through every room on the first floor before taking the stairs to the second floor. You visit every "column" in one "row" before moving down the hall to the next.

This linear layout is why C arrays are so fast—the CPU can simply stream the data in one continuous direction rather than jumping around to different corners of your memory.

Key takeaway

C stores multi-dimensional arrays in row-major order, meaning it lays out all elements of the first row, then the second, in one continuous line in memory.