Fiveable
Fiveable

6.2 Multi-dimensional arrays

4 min readLast Updated on August 13, 2024

Multi-dimensional arrays in C let you store data in grid-like structures. They're super useful for representing tables, matrices, and other complex data. You can create, access, and manipulate these arrays easily, making them a powerful tool in your programming toolkit.

Understanding how multi-dimensional arrays work in memory is key. They're stored in contiguous memory locations, which affects how you access and work with them. This knowledge helps you write more efficient code and avoid common pitfalls when using these arrays.

Two-Dimensional Arrays in C

Declaration and Initialization

Top images from around the web for Declaration and Initialization
Top images from around the web for Declaration and Initialization
  • Declare two-dimensional arrays using the syntax:
    data_type array_name[rows][columns]
    • The
      data_type
      specifies the type of elements stored in the array (int, float, char, etc.)
    • array_name
      is the identifier used to refer to the array
    • rows
      and
      columns
      define the dimensions of the array
  • Initialize two-dimensional arrays at declaration using nested braces
    • Example:
      int arr[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}
    • Each inner set of braces represents a row of the array
    • Elements within each row are separated by commas
  • Partially initialize arrays and remaining elements are automatically set to zero
    • Example:
      int arr[3][4] = {{1, 2}, {5, 6}}
    • Uninitialized elements in the first two rows are set to 0
    • The entire third row is also filled with 0s
  • Omit the size of the first dimension (rows) during declaration if the array is initialized simultaneously
    • Example:
      int arr[][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}}
    • The compiler infers the number of rows based on the initialization
  • Dynamically allocate two-dimensional arrays using pointers and the
    malloc()
    function
    • Example:
      int **arr = (int **)malloc(rows * sizeof(int *));
    • Allocate memory for each row separately using additional
      malloc()
      calls

Accessing and Modifying Array Elements

  • Access elements in a two-dimensional array using the array name followed by two sets of square brackets
    • Example:
      arr[i][j]
      accesses the element at row
      i
      and column
      j
    • The first index (
      i
      ) represents the row, and the second index (
      j
      ) represents the column
  • Use zero-based indexing in C, so the first element is accessed using
    arr[0][0]
    • Example: In a 3x4 array, the first element is
      arr[0][0]
      , and the last element is
      arr[2][3]
  • Modify elements by assigning new values to specific indices
    • Example:
      arr[1][2] = 10
      assigns the value 10 to the element at row 1 and column 2
  • Be cautious of out-of-bounds access to array elements
    • Accessing elements beyond the declared dimensions leads to undefined behavior
    • Out-of-bounds access can cause program crashes or security vulnerabilities

Traversing Arrays with Nested Loops

Iterating Over Rows and Columns

  • Traverse a two-dimensional array using nested loops, typically two
    for
    loops
    • The outer loop iterates over the rows, while the inner loop iterates over the columns within each row
    • Example:
      for (int i = 0; i < rows; i++) {
          for (int j = 0; j < columns; j++) {
              // Access element at arr[i][j]
          }
      }
      
  • Use loop variables (
    i
    and
    j
    ) to access individual elements of the array
    • The outer loop variable (
      i
      ) represents the current row
    • The inner loop variable (
      j
      ) represents the current column within the row
  • Base the outer loop condition on the number of rows and the inner loop condition on the number of columns
    • Example:
      i < rows
      for the outer loop and
      j < columns
      for the inner loop
    • Ensures that all elements within the array are accessed

Performing Operations on Array Elements

  • Traverse the array to perform operations on each element
    • Print the values of the elements
    • Search for specific elements or patterns
    • Modify the values of elements based on certain conditions
  • Example: Printing the elements of a 2D array
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            printf("%d ", arr[i][j]);
        }
        printf("\n");
    }
    
  • Example: Finding the maximum element in a 2D array
    int max = arr[0][0];
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            if (arr[i][j] > max) {
                max = arr[i][j];
            }
        }
    }
    

Memory Layout of Multi-Dimensional Arrays

Contiguous Memory Storage

  • Store multi-dimensional arrays in contiguous memory locations in C
    • The elements are laid out in a row-major order
    • Elements of each row are stored consecutively in memory
  • Example: Memory layout of a 3x4 array
    arr[0][0] arr[0][1] arr[0][2] arr[0][3]
    arr[1][0] arr[1][1] arr[1][2] arr[1][3]
    arr[2][0] arr[2][1] arr[2][2] arr[2][3]
    
  • Calculate the memory address of an element
    arr[i][j]
    using the formula:
    • &arr[i][j] = base_address + (i * num_columns + j) * sizeof(data_type)
    • base_address
      is the memory address of the first element of the array
    • num_columns
      is the number of columns in the array
    • sizeof(data_type)
      is the size of each element in bytes

Efficient Memory Access and Function Parameters

  • Understand the memory layout for efficient memory access and optimization
    • Accessing elements sequentially in row-major order can improve cache performance
    • Traversing the array in the order of memory layout can minimize cache misses
  • Pass multi-dimensional arrays to functions as pointers to the first element of each row
    • Example:
      void function(int arr[][num_columns], int rows)
    • The number of columns must be specified to determine the memory offset between rows
    • The array decays to a pointer to the first element of each row when passed to a function
© 2025 Fiveable Inc. All rights reserved.
AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.


© 2025 Fiveable Inc. All rights reserved.
AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.

© 2025 Fiveable Inc. All rights reserved.
AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.
Glossary
Glossary