Apr 14, 20232D Arrays in C Tutorial 3Accessing elements in a 2D Arrays
William Huynh βΈ± 2 min read

Accessing elements in a 2D Array πŸ“š

Preface 🐢

Whats the fun in storing elements in a 2D array if we can't access the elements? πŸ˜› Here we will learn how to access the elements in a 2D array.

Getting Started πŸŽ‰

To access an element in a 2D array you need two things!

  • The row index
  • The column index

With those two things we can access any element!

Remember that indexes start at 0, so the first row and first column will have indexes of 0.

Some Practice 🎯

Say we have the following array:

int my_array[2][4] = {
  {1, 2, 3, 4}, // First row
  {5, 6, 7, 8} // Second row
};

Let's see if we can identify the row and column indexes of each element!

Try work it out yourself first, before clicking the dropdown answer :P

Element 1> Element 1 is at [0, 0] !

Element 2> Element 2 is at [0, 1] !

Element 4> Element 4 is at [0, 3] !

Element 5> Element 5 is at [1, 0] !

Element 6> Element 6 is at [1, 1] !

Element 8> Element 8 is at [1, 3] !

Well done!

Writing the code ✍️

So luckily writing the code to access an element is very similar to our thought process above - we need the row and column indexes of the element we want to access!

For example, if I wanted to access the element in the first row and second column, I would do the following:

int my_num = my_array[0][1];

This creates an integer variable called my_num, and assigns it the value of whatever element is stored at my_array[0][1].

Pretty easy right?

βœ… Now lets get started on Editing an element 😎