TYPE array_var_name[SIZE]; // Uninitialized TYPE array_var_name[SIZE] = {value1, value2, ...}; // Initialized TYPE array_var_name[] = {value1, value2, ...}; // Initialized with size of // array determined by number // of items in initialization |
So the indices of an array of size N are 0..N-1
int i; for (i = 0; i < N; i = i + 1) { A[i]... } |
For example, a two dimensional array can be imagined as a Two dimensional table of a certain data type:
jimmy is an two dimensional array of 3x5 values of type int.
The way to declare this array is:
int jimmy [3][5]; |
int A[10][5][20]; |
A[0][0] | A[0][1] | A[0][2] | A[0][3] | A[0][4] |
A[1][0] | A[1][1] | A[1][2] | A[1][3] | A[1][4] |
A[2][0] | A[2][1] | A[2][2] | A[2][3] | A[2][4] |
stored as:
A[0][0] | A[0][1] | A[0][2] | A[0][3] | A[0][4] | A[1][0] | A[1][1] | ... | A[2][3] | A[2][4] |
A[0][0] | A[0][1] | A[0][2] | A[0][3] | A[0][4] |
A[1][0] | A[1][1] | A[1][2] | A[1][3] | A[1][4] |
A[2][0] | A[2][1] | A[2][2] | A[2][3] | A[2][4] |
stored as:
A[0][0] | A[1][0] | A[2][0] | A[0][1] | A[1][1] | A[2][1] | A[0][2] | ... | A[1][4] | A[2][4] |
int jimmy[3][5]; |
is equivalenet to: int jimmy[3*5]; |
jimmy[i][j] |
is equivalenet to: jimmy[i*5+j] |
It may sound strange that you can pass an entire array by reference...
But due to the fact that arrays are stored in row major manner, if we know:
 
 
|
Then we can find the location of any element of that array.
int main(int argc, char *argv[]) { void Print(float [][4]); // How to declare function // with ARRAY parameter // NOTE: parameter and the // first dimension is NOT // required // You MAY write: // void Print(float X[3][4]); float A[3][4]; int i, j, k; k = 1; for (i = 0; i < 3; i = i + 1) for (j = 0; j < 4; j = j + 1) { A[i][j] = k; k = k + 1; } Print(A); // How to pass ARRAY parameter } void Print(float H[3][4]) // How to define function // with array parameter // NOTE: first dimension is IGNORED // by the compiler... { int i, j, k; for (i = 0; i < 3; i = i + 1) { for (j = 0; j < 4; j = j + 1) cout << H[i][j] << "\t"; cout << "\n"; } } |