2D Arrays in Small-C

Authors

Publication

Pub Details

Date

Pages

See all articles from QL Hacker's Journal 5

In a recent article in The C Users Journal, Don Lang discusses how to implement 2D arrays on C. His article covers code that when added to the original Small-C source, allows Small-C to support 2D arrays.

Since the source code for the QL’s Small-C compiler is not available, we could not use the code he provides. But he does discuss a not-so-elegant way of implementing 2D arrays. Since memory is really a 1D array, the computer figures out where in memory an element of an array is. This can be easily done in Small-C.

Given an array of size MAX_X, and elements starting at 0, then (x,y) is equal to (( x * MAX_X ) + y). Below is a sample Small-C program that demonstrates this:

/*  Two Dimensional Arrays in Small-C

For an array of [10][5] let MAX_X = 10

Assumptions: Arrays start at 0. For an
array of size 10, range is 0..9.

Way to address the cell at x,y:
temp = array[(x*MAX_X)+y];

*/

#define MAX_X 10

main() {

int array[100]; /* 10x10 array */
int x,y;

for (x = 0; x <= 9; x++) {
for (y = 0; y <= 9; y++) {
array[(x*MAX_X)+y] = x*y;
printf("%d ",array[(x*MAX_X)+y]);
}
printf("\n");
}

}

Products

 

Downloadable Media

 

Image Gallery

Scroll to Top