C Two-dimensional Arrays

Beginner
6 min read
Updated: Nov 2026
1 example

What Is Two-dimensional Arrays?

A two-dimensional array is an array of arrays. int m[2][3] has 2 rows of 3 columns. C stores it in row-major order, so m[0][0..2] come first, then m[1][0..2]. Use nested loops to visit every cell.

Remember
int m[2][3] = {
    {1, 2, 3},
    {4, 5, 6}
};
m[1][2] = 60;    /* row 1, column 2 */

Cheat Sheet

Keep these facts handy while you work with Two-dimensional Arrays in C.

TopicDetail
Declaretype name[rows][cols];
Accessm[row][col]
LayoutRow-major in memory
Total sizerows * cols * sizeof(type)

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Multidimensional Arrays.

Example 1 — Print a matrix and its row sums

Nested loops over rows and columns.

C
#include <stdio.h>

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

    for (int r = 0; r < 2; r++) {
        int sum = 0;
        for (int col = 0; col < 3; col++) {
            printf("%d ", m[r][col]);
            sum += m[r][col];
        }
        printf("| sum=%d\n", sum);
    }
    return 0;
}

How It Works

  1. The outer loop picks the row, the inner loop walks its columns.
  2. sum is reset for each row.
  3. Row sums: 1+2+3 = 6 and 4+5+6 = 15.

Edge Cases & Pitfalls

Check these before relying on Two-dimensional Arrays in real programs.

swap

Mixing up row and column

m[col][row] compiles but reads the wrong cell. Name the loop variables r and c.

param

Missing column count in functions

A function parameter must specify all but the first dimension: int m[][3].

Key Takeaways

  • Shape: [rows][cols].
  • Order: row-major layout.
  • Loops: nest them for traversal.

One line: A two-dimensional array is an array of arrays.

Frequently Asked Questions

Use two sizes: int grid[3][4]; creates 3 rows and 4 columns. Initialize it with nested braces.
In row-major order: all elements of row 0, then row 1, and so on, in one contiguous block.
Continue with "C Multidimensional Arrays" next. Go beyond two dimensions: 3D arrays, indexing, and memory layout. The C Arrays hub lists every topic in order.

Next: Multidimensional Arrays

Go beyond two dimensions: 3D arrays, indexing, and memory layout.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful