/* arrays2d.c Jeff Ondich, 6 Jan 2022 Demonstrating the strange world of 2-dimensional arrays in C. */ #include #include #define MAX_ROW_COUNT 30 #define MAX_COLUMN_COUNT 50 void fill_grid(char grid[][MAX_COLUMN_COUNT], int row_count, int column_count); void swap_rows(char grid[][MAX_COLUMN_COUNT], int row_index_1, int row_index_2, int column_count); void print_grid(char grid[][MAX_COLUMN_COUNT], int row_count, int column_count, FILE *output_stream); int main(int argc, char *argv[]) { // Start with a 2D array, fill it with some stuff, and swap // a couple rows before printing the results. We're allocating // the memory statically here in main, but we'll discuss doing // the allocation dynamically (i.e. with malloc) on another day. char grid[MAX_ROW_COUNT][MAX_COLUMN_COUNT]; int row_count = 8; int column_count = 30; fill_grid(grid, row_count, column_count); printf("Before:\n"); print_grid(grid, row_count, column_count, stdout); swap_rows(grid, 1, 6, column_count); printf("After:\n"); print_grid(grid, row_count, column_count, stdout); return 0; } // Fills the grid with a row of A's, a row of B's, etc. up to row_count. Only // columns up to column_count are filled (the rest of the allocated space, if // any, is left unchanged. void fill_grid(char grid[][MAX_COLUMN_COUNT], int row_count, int column_count) { char ch = 'A'; for (int row = 0; row < row_count; row++) { for (int column = 0; column < column_count; column++) { grid[row][column] = ch; } ch++; } } // Swaps the contents of the specified rows in the grid (only swapping column data // up to the specified column count). void swap_rows(char grid[][MAX_COLUMN_COUNT], int row_index_1, int row_index_2, int column_count) { for (int column = 0; column < column_count; column++) { char saved_char = grid[row_index_1][column]; grid[row_index_1][column] = grid[row_index_2][column]; grid[row_index_2][column] = saved_char; } } // Prints the contents of the grid (only printing data stored in the specified // range of rows and columns). void print_grid(char grid[][MAX_COLUMN_COUNT], int row_count, int column_count, FILE *output_stream) { for (int row = 0; row < row_count; row++) { for (int column = 0; column < column_count; column++) { fputc(grid[row][column], output_stream); } fputc('\n', output_stream); } fputc('\n', output_stream); }