Multi-Dimensional Arrays in C, Explained with Code Examples

UPI Study › Courses › Programming in C › Free lessons › Lesson 7.4 Free with a free account

Multi-Dimensional Arrays in C

Programming in C · Chapter 7: Arrays, Strings, Input Validation, and Formatted OutputSection 7.4 · lesson 43 of 786 min · free with a free account

← Passing Arrays to Functions in CNext lesson: String Representation in C →

Earn 3 college credits for Programming in CRecommended for credit by NCCRS · Computer Science 240 · self-paced · one payment, lifetime access

In this lesson

Declaring, looping over, storing, and passing two-dimensional arrays in C.

  • Declare and initialize a two-dimensional array with nested braces
  • Use nested loops to visit every element of a grid
  • Calculate an element's position in row-major order
  • Write a function parameter for a 2D array that includes the column size

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (762 words). Read along, or search it.

Opening Question

Tallying Plays Across Floors and Machines

Starlight Arcade has three floors, and each floor has four machines. A tally of plays for that isn't a line. It's a grid, with rows and columns, like a seating chart or a game board. How do you store a grid in C? C can store one directly. It's called a two-dimensional array, and a loop inside a loop visits every square.

Declaring a Grid

Rows First, Then Columns

A two-dimensional array has two sizes: first the number of rows, then the number of columns. Plays three by four is three rows of four boxes, twelve in all. To start it with braces, give each row its own inner pair of braces. That keeps the picture easy to see in your code. To reach one box, give two indexes: row first, then column. Both start at zero. So plays one two is row one, column two: the third machine on the second floor.

Nested Loops

A Loop Inside a Loop Visits Every Box

To visit every square, put a loop inside a loop. The outer loop picks the row, and the inner loop runs along that row's columns. The inner loop runs all four times, for each single pass of the outer loop. And floor total starts again at zero for every row, so each floor gets its own total. Run it. Plays one two is eleven. Then the twelve boxes print one row at a time: totals forty-three, forty-one, and thirty-five. Swap the indexes by mistake, and you reach a different box: plays two one is three, not eleven.

Memory Layout

Row-Major Order in One Long Line

But computer memory is one long line, not a grid. So C stores a 2D array row after row: all of row zero, then row one, then row two. That's called row-major order. Box r, c sits at position r times the number of columns, plus c. So plays one two is box six from the start: one full row of four, plus two.

Sizeof at Every Level

Grid, Row, and Box Sizes

The sizes follow the same shape. The whole grid is an array of three rows, and each row is itself an array of four ints. So sizeof works on every level. Sizeof plays is the whole grid, sizeof plays zero is one row, and sizeof plays zero zero is one box. Run it. Forty-eight bytes for twelve boxes, sixteen for one row, three rows, and four columns. Row-major order also explains a practical habit: an inner loop on the column reads memory in the same order it's stored.

Quick Check

Counting Seats in Row-Major Order

Quick check. A new grid, seats, has four rows of five. Nested loops number the boxes zero, one, two, in the order they're visited. What does seats two three hold? Pause and predict. Thirteen. Two full rows of five come first, that's ten boxes, and then three more in row two. The loops visit boxes in row-major order, so the count is r times five, plus c. Eleven would use the row count, four, in place of five.

Passing a Grid

The Column Size Must Be Written

A grid passes to a function like a one-dimensional array: the function gets the address of the first box. There's one new rule. To find grid r c, the function must know how long a row is. So the column size must be written in the parameter. The row count can stay empty, and travel as its own number. This function walks down one column, adding as it goes. Run it. Column zero is twelve plus four plus eight: twenty-four plays. Now forget the column size. Clang refuses: array has incomplete element type. Only the first size may be left empty.

Three Dimensions

A Stack of Grids With Three Indexes

You can add a third size. Toys two by two by three is two buildings, each a grid of two floors by three machines. Think of a stack of grids. Three indexes pick one box, and a triple-nested loop visits them all: one loop per index. Run it. Toys one, zero, two is building one, floor zero, machine two: the nine. And all twelve toys add up to seventy-eight. You'll rarely need more than three dimensions, but the rule never changes.

Common Mistake

An Outer Loop That Counts Too Far

Priya's floor report once added up the right numbers, but then tried a fourth row. Sam spotted why: her outer loop counted to four, not three. Row three is past the end of the grid, so whatever it shows is undefined behavior. Count rows first, then columns, Sam said.

Key Takeaways

Rows, Columns, and One More Index

To recap. A 2D array has rows, then columns, and two indexes reach one box: row first, then column. Nested loops visit every box, and C stores the grid row after row, in row-major order. A function needs the column size written in its parameter. And a 3D array just adds one more index, and one more loop.

About Programming in C at UPI Study

Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: C vs C++

Why take it here

Why students take Programming in C with UPI Study

How programs work close to the machineProgramming in C teaches how a program uses memory: variables and data types, control flow, functions, arrays and strings, pointers, files, structures and dynamic memory. C is the base for operating systems, embedded devices and many computer-science courses.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Programming in C carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Multi-Dimensional Arrays in C

How do you declare a two-dimensional array in C?
Give two sizes, rows first and then columns: int plays[3][4]; makes 3 rows of 4 ints, 12 elements in all. To initialize it, give each row its own inner braces, like {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}. To reach one element, write the row index and then the column index, both starting at zero, so plays[1][2] is row 1, column 2.
How is a 2D array stored in memory in C?
C stores a 2D array in row-major order: all of row 0, then all of row 1, and so on, in one continuous line of memory. Element [r][c] sits at position r times the number of columns plus c. In an array with 4 columns, element [1][2] is at position 1 * 4 + 2 = 6. That is why an inner loop over the column reads memory in stored order.
Why must you give the column size when passing a 2D array to a function in C?
The function needs the row length to find element [r][c], because that element sits r full rows plus c elements from the start. So the column size must appear in the parameter, as in int column_total(int grid[][4], int rows, int col). Only the first size may be left empty, and the row count travels as its own argument. Leaving out the column size gives an incomplete element type error.
What does sizeof return for a 2D array in C?
sizeof works at each level of a 2D array. For int plays[3][4] with 4-byte ints, sizeof plays is 48 bytes for the whole grid, sizeof plays[0] is 16 bytes for one row, and sizeof plays[0][0] is 4 bytes for one element. Dividing recovers the shape: 48 / 16 gives 3 rows, and 16 / 4 gives 4 columns.

About the Programming in C course

How many college credits is Programming in C?
Programming in C (Computer Science 240) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Programming in C cost and what is included?
$250, paid once, with lifetime access: all 78 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Programming in C take?
It is self-paced with no deadlines. The 78 lessons total about 9 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Programming in C.

78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Programming in C
3 credits · NCCRS
Enroll →