DataType var[ size ]; // One dimensional array DataType var[ size1 ][ size2 ]; // Two dimensional array |
double a[10]; // array of 10 double variables |
Result:
Notice that:
|
|
extern DataTyp arrayVarName [ ] ; |
File where the array is defined | Declaring the (global) array variable |
---|---|
double a[10]; // Array definition void func( ); // Declare func( ) int main( int argc, char* argv[] ) { int i; for ( i = 0; i < 10; i++ ) a[i] = i*i; func( ); } |
extern double a[ ]; // Array declaration void func( ) { int i; for ( i = 0; i < 10; i++ ) printf("a[%d] = %lf\n", i, a[i]); } |
How to run the program:
|
extern double a[ ] ; |
The C compiler will handle accessing the array element a[i] as follows:
|
|
File where the array is defined | Declaring the (global) array variable |
---|---|
double a[10]; // Array definition void func( ); // Declare func( ) int main( int argc, char* argv[] ) { int i; for ( i = 0; i < 10; i++ ) a[i] = i*i; func( ); } |
extern double a[10]; // Array declaration void func( ) { int i; for ( i = 0; i < 10; i++ ) printf("a[%d] = %lf\n", i, a[i]); } |
DataType arrayVarName [ size1 ] [ size2 ] ; |
Example: (array definition)
double a[3][5]; |
extern DataType arrayVarName [ ] [ size2 ] ; |
File where the array is defined | Declaring the 2-dim. array variable |
---|---|
double a[3][5]; // Array definition void func( ); // Declare func( ) int main( int argc, char* argv[] ) { int i, j; for ( i = 0; i < 3; i++ ) for ( j = 0; j < 5; j++ ) a[i][j] = i + j; func( ); } |
extern double a[ ][5]; // Array declaration void func( ) { int i; for ( i = 0; i < 3; i++ ) { for ( j = 0; j < 5; j++ ) printf("a[%d][%d] = %lf ", i, j, a[i][j]); putchar('\n"); } } |
How to run the program:
|
|
Example: double a[3][5] is stored in memory as follows:
As you can see from the above figure:
address of a[i][j] = base-address + ( i*SIZE-of-the-2nd-dimension + j ) * 8 |
|
File where the array is defined | Declaring the 2-dim. array variable |
---|---|
double a[3][5]; // Array definition void func( ); // Declare func( ) int main( int argc, char* argv[] ) { int i, j; for ( i = 0; i < 3; i++ ) for ( j = 0; j < 5; j++ ) a[i][j] = i + j; func( ); } |
extern double a[3][5]; // Array declaration void func( ) { int i; for ( i = 0; i < 3; i++ ) { for ( j = 0; j < 5; j++ ) printf("a[%d][%d] = %lf ", i, j, a[i][j]); putchar('\n"); } } |