Created: 2023-01-15 13:09
Status: #concept
Subject: Programming
Tags: C C Array One-Dimensional Array Pointer Arithmetic

Multidimensional Array

Description

They are Arrays that are stored in Row-Major Order, with rows denoting each array and columns for the respective array indices.

Syntax

We have to specify the number of [rows] then [columns].

  • we can access them like single-dimension arrays, but we need to specify the array[row][col].

Multidimensional Array Row & Columns.png

Row Major Order

Multidimensional arrays are stored internally as normal 1d arrays positioned beside each other.

Multidimensional Array Illustration.png

*p points to an an object of size int (*)[3], “an integer array with 3 elements each”. this makes the pointer shift sizeof(int) * 3 elements everytime we do p++.

Multidimensional String Arrays

Remember, when declaring 2d arrays, we must always specify the COLS (the length of each string), but not necessarily ROWS.

char planets[][8] = { "Mercury", "Venus", "Earth", "Mars", "Juputer", "Saturn", "Uranus", "Neptune", "Pluto"};

Multidimensional String Array.png

Ragged Arrays

A ragged array is an array of Pointer Variables char *str[] whose elements are pointers to Constant strings *str.

  • they are the data type of the int main(int argc, char *argv[]) to accept CLI arguments.

int main(void)
{
  char *planets[] = {"Mercury", "Venus", "Earth"};

  printf("%s", planets[1]); // outputs Mercury
  printf("%s", *(planets+2)); // outputs Earth 

  printf("%c", planets[0][0]); // outputs M
  printf("%c", *(planets+2)[0]); // outputs E
}

Ragged Arrays Example.png

References