Using a typedef array to declare an array
Ok, I'm looking into 2D arrays right now and I'm confused about the dimensions of a 2D array, if the situation is like this:
#define ROW 5
#define COL 10
typedef int arrint[COL]
and it is declared in the main function like this:
arrint a2D[ROW]
Is it a 2D array a2D[5][10]
or a2D[10][5]
?
Since you declared arrint to be int [COL == 10] and a2D is an array of 5, so you got the equivalent:
int a2D[5][10];
Typedef is fine to use, but it is better to type a 2D array as a 2D array to avoid confusion. In C, two-dimensional arrays are stored in memory as primary. Read this article for a good explanation. Arrays are arranged in memory in such a way that the first line appears first, then the second, etc. Each line consists of COL elements, so the way to define this would be as follows:
typedef int A2D[ROW][COL];
A2D a2d = {0}; // Declares 2D array a2d and inits all elements to zero
Then to access the element in row i in column j use:
a2d[i][j]
Here's a sample program:
#include <stdio.h>
#define ROW 5
#define COL 10
typedef int A2D[ROW][COL];
int main(int argc, char** argv)
{
A2D a2d = {0};
int r,c;
a2d[1][2] = 12;
for(r=0; r<ROW; r++)
{
printf("Row %d: ", r);
for(c=0; c<COL; c++)
printf("%2d ", a2d[r][c]);
printf("\n");
}
}
This leads to the following output:
Row 0: 0 0 0 0 0 0 0 0 0 0
Row 1: 0 0 12 0 0 0 0 0 0 0
Row 2: 0 0 0 0 0 0 0 0 0 0
Row 3: 0 0 0 0 0 0 0 0 0 0
Row 4: 0 0 0 0 0 0 0 0 0 0