I have been able to come up with following ways of sending a 2-d array to the function:
#include <stdio.h>
# define NUM_TWO_DIM_ROWS 3
# define NUM_TWO_DIM_COLS 5
void iterate_two_dim(int[][NUM_TWO_DIM_COLS]);
void iterate_two_dim1(int (*)[NUM_TWO_DIM_COLS]);
void iterate_two_dim2(int *);
int main() {
int two_dim[][NUM_TWO_DIM_COLS] = { //note the second dimension needs to be specified to resolve expression like two_dim[1]
{1,2,3,4,5}, // second dimension tells how many integers to move the two_dim pointer
{6,7,8,9,10},
{11,12,13,14,15}
};
iterate_two_dim(two_dim);
iterate_two_dim1(two_dim);
iterate_two_dim2(*two_dim);
}
void iterate_two_dim(int two_dim[][NUM_TWO_DIM_COLS]) { //function parameter uses array notation
printf("Two dim array passed using array notation\n" );
for(int row = 0; row < NUM_TWO_DIM_ROWS; row++) {
for(int col = 0; col < NUM_TWO_DIM_COLS; col++) {
printf("two_dim[%d][%d] = %-4d ", row,col, two_dim[row][col] );
}
printf("\n");
}
printf("\n");
}
void iterate_two_dim1(int (*two_dim)[NUM_TWO_DIM_COLS]) { //function parameter uses pointer notation
printf("Two dim array passed using pointer notation\n" );
for(int row = 0; row < NUM_TWO_DIM_ROWS; row++) {
for(int col = 0; col < NUM_TWO_DIM_COLS; col++) {
printf("two_dim[%d][%d] = %-4d ", row,col, two_dim[row][col] );
}
printf("\n");
}
printf("\n");
}
void iterate_two_dim2(int *two_dim) { //function parameter uses pointer notation
printf("Two dim array passed using pointer notation\n" );
char buffer[100];
for(int count = 0; count < NUM_TWO_DIM_ROWS * NUM_TWO_DIM_COLS; count++) {
if(count > 0 && count % NUM_TWO_DIM_COLS == 0 )
printf("\n");
snprintf(buffer, 40, "two_dim[%d] = %2d", count, two_dim[count] );
printf("%-20s", buffer );
}
printf("\n");
}
Any other ways one can think of for this code where array two_dim is declared and initialized as shown?