1 December

Arrays as function parameters, 2-D arrays

#include <stdio.h>

/* Arrays as function parameters

Normally we pass single variables to functions.
void f(int x);

Can also pass an array:
*/
const int SIZE = 6;
void f(int x[]){} // size unspecified, ok
void g(int x[SIZE]){} // size specified, ok
void h(int x[10]){} // ok
int main2() {
int array[SIZE]; // create array
f(array); // okay
g(array); // okay
h(array); // size mismatch, but compiler doesn't care.
return 0;
}
/* Passing array behaves differently than
other parameters. It's more like call by
reference.
*/
void ff(int x, int& y, int a[3])
{
x = 4;
y = 5;
a[0] = 6;
a[1] = 7;
a[2] = 8;
}

int main3()
{
int c = 99;
int d = 98;
int a[3] = { 97, 96, 95 }; // array initialization
printf("%d,%d,%d,%d,%d\n",c,d,a[0],a[1],a[2]);
ff(c, d, a);
printf("%d,%d,%d,%d,%d\n",c,d,a[0],a[1],a[2]);
// The function ff CAN change the values
// of the array, just like it can change
// the reference parameter.
return 0;
}


/* Two-dimensional arrays.

So far, arrays have been one-dimensional.
int a[5] = {0,1,2,3,4,5};
Represented by one row of boxes.

int b[5][3]; // 5 rows, 3 columns

Diagram:
0 1 2
0 [0][0] [0][1] [0][2]
1 [1][0] etc.
2
3
4

More dimensions possible, but rare.
Imagine 3 dimensions as a stack of paper,
with a 2-D grid on each sheet. Then,
a[3][5][2] would refer to sheet 3, row 5, column 2
*/

int main4()
{
const int ROWS = 18;
const int COLS = 8;
int grid[ROWS][COLS];
// Let's initialize it to a multiplication
// table.
for(int i = 0; i < ROWS; i++)
{
for(int j = 0; j < COLS; j++)
{
grid[i][j] = (i+1) * (j+1);
}
}
// print out entire grid
for(int i = 0; i < ROWS; i++)
{
for(int j = 0; j < COLS; j++)
{
printf("%5d ", grid[i][j]);
}
printf("\n");
}
return 0;
}

Help on assignment

See the experimentation in main. It’s your job to combine these function definitions and hints with the structure already given on the assignment page.

/* Output the grid onto the screen using printf. */
void output_grid (char grid[M][N])
{
for(int i = 0; i < M; i++)
{
for(int j = 0; j < N; j++)
{
printf("%c", grid[i][j]);
}
printf("\n");
}
}

// Fill grid with . character
void initialize_grid(char grid[M][N])
{
int j; int i;
for (i = 0; i < M ; i++)
{
for (j = 0; j < N; j++)
{
grid [i] [j]= ('.');
}
}
}

int main()
{
char grid[M][N];
srand(time(NULL));
initialize_grid(grid);
// some experimentation
int i = 2;
int j = 3;
char letter = 'A';
grid[i][j] = letter;
i++; // move down
letter++; // next letter
grid[i][j] = letter;
j++; // move right
letter++; // next letter
grid[i][j] = letter;
// You'll need to loop thru letters.
while(letter < 'Z')
{
letter++;
printf("%c", letter);
}
printf("\n");
// TODO
output_grid(grid);
return 0;
}

©2011 Christopher League · some rights reserved · CC by-sa