Reputation: 169
Okay i'm currently studying 2D arrays and I'm confused as to what the dimensions are of a 2D array if the situation is this:
#define ROW 5
#define COL 10
typedef int arrint[COL]
and it's declared in the main function as this:
arrint a2D[ROW]
Is the 2D array a2D[5][10]
or a2D[10][5]
?
Upvotes: 3
Views: 276
Reputation: 1556
Since you have declared arrint to be an int[COL==10], and a2D is an array of 5 of those, so you have ended up with the equivalent of:
int a2D[5][10];
Typedef is fine to use, but better to typedef a 2D array as a 2D array to avoid confusion. In C, two-D arrays are stored in memory as row-major. Read this post for a good explanation. Arrays are arranged in memory such that the first row appears first, followed by the second and so on. Each row consists of COL elements, so the way to define this would be:
typedef int A2D[ROW][COL];
A2D a2d = {0}; // Declares 2D array a2d and inits all elements to zero
Then to access the element at row i, column j, use:
a2d[i][j]
Here is 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 produces 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
Upvotes: 4