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]
.
int m[5][9];
initializes a 2d multidimensional array with5
rows and9
columns.
Row Major Order
Multidimensional arrays are stored internally as normal 1d arrays positioned beside each other.
How do we replace nested for loops with Pointers in Multidimensional Arrays?
for(int *p = *a; p < *a + ROWS * COLS; p++)
This works since adding a number i
to a multidimensional array pointer a will add i * NUM_ROWS
worth of elements to the array's Memory Address.
Example
int arr[2][3], *p = a;
*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"};
- there is a lot of wasted space due to declaring the length of each string as
[8]
.
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
}
References
- C Programming, A Modern Approach, 2nd Edition, Chapter 12.4