- Write loops to initialize:
int i,j,k = 0;
for(i = 0; i < MAX_ROWS; i++)
for(j = 0; j < MAX_COLS; j++)
a[i][j] = k++;
-
We could also open a file containing the initial data and read it into
the array:
int i,j;
FILE *fp;
if((fp = fopen("file","r")) == NULL)
{ fprintf(stderr,"Unable to open file\n");
exit(1);
}
for(i = 0; i < MAX_ROWS; i++)
for(j = 0; j < MAX_COLS; j++)
fscanf(fp, "%d", &a[i][j]);
fclose(fp);
-
We can also use an array initializer like we did for 1D arrays.
Here it is helpful to think of the 2D array as a 1D array whose
elements are 1D arrays.
(recall the
picture).
int a[MAX_ROWS][MAX_COLS] = { {1,2,3},
{4,5,6},
{7,8,9} };