C programming declare global array
DataType var[ size ]; // One dimensional array DataType var[ size1 ][ size2 ]; // Two dimensional array
double a[10]; // array of 10 double variables
- Declaring a variable = Provide sufficient information to the C compiler to access the variable in memory.
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[] )
extern double a[ ]; // Array declaration void func( )
- The main Prog file: click here
- The array declaration Prog file: click here
How to run the program:
Suppose the C compiler processed the following array declaration :
extern double a[ ] ;
The C compiler will handle accessing the array element a[i] as follows:
It generate a dummy base address X (that the linker must update)
The C compiler will ignore any text between the brackets [. ] in an array declaration :
extern DataType arrayVarName [ /* ignored ! */ ] ;
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[] )
extern double a[10]; // Array declaration void func( )
Recall the syntax to define a two -dimensional array :
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[] )
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"); >>
- The main Prog file: click here
- The array declaration Prog file: click here
How to run the program:
- The C compiler stores a 2-dimensional array in a row -wise fashion inside the computer memory
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
The C compiler will ignore any text between the brackets [. ] in the leading (first) dimenison of an array declaration :
extern DataType arrayVarName [ /* ignored ! */ ] [ SIZE ] ;
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[] )
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"); >>