APS105 L20 - 2D Arrays

#APS105 Slides Lecture

1D Arrays

We learn this already in L13. They syntax must follow:


2D Arrays

Syntax for 2D arrays is:

To declare a 2D array that's 2 x 3:

Example: Working with a simple 2D array

#include <stdio.h>
#include <stdlib.h>
#define NUM_ROWS 2
#define NUM_COLS 3
int main(void) {
	int table[NUM_ROWS][NUM_COLS] = { // we are setting the values for the array
		{1,2,3}, // each row here is a row in the array
		{4,5,6}
	}; 
	for (int i = 0; i < NUM_ROWS; ++i) {
		for (int j = 0; j < NUM_COLS; ++j) {
			printf("table[%d][%d] = %d\n", i, j, table[i][j]);
		}
	}
	return EXIT_SUCCESS;
}

We can also initialize the array with a csv that sets each individual element, but this is bad practice because it is ugly af.


2D arrays in C are stored in row-major order.

This means that each element in the array is stored with indices that are directly adjacent.
For example, the following are equivalent:

table[0][0] -> table[0]
table[0][1] -> table[1]
table[0][2] -> table[2]
table[1][0] -> table[3]
table[1][1] -> table[4]
table[1][2] -> table[5]

And thus, table[i][j] has the same address in memory as table + i * NUM_COLS + j.

Note that you can only omit the number of rows when declaring an array.

Thus, int table[][3] is valid, but not table[][] or table[3][].
In larger-dimension arrays, only the first dimensions can be unspecified in the declaration.


Using dynamic lengths in function arguments

You could write a function prototype as follows:

void foo(int numRows, int numCols, int table[][numCols]);

You must declare the variable used in the array declaration before the array declaration itself.

Creating a 2D array with different-sized columns

We can do this by using malloc.

#include <stdio.h>
int main(void) {
	printf("Number of rows: ");
	int numRows = inputLength();
	int *table[numRows];
	for (int i = 0; i < numRows; ++i) {
		printf("Number of columns: ");
	int numCols = inputLength();
	table[i] = malloc(
		sizeof(int) * (numCols + 1)
	);
	for (int j=0; j<numCols; ++j) {
		table[i][j] = rand() % 100 + 1;
	}
	table[i][numCols] = -1;
	}
	return EXIT_SUCCESS;
}