DataType arrayName [ SIZE ]; // Defines an array FunctionName ( ...., arrayName , ... ) // Pass the array arrayName as a parameter |
int main( int argc, char* argv[] ) { double a[10]; int i; for ( i = 0; i < 10; i++ ) a[i] = i; func( a ); } |
returnType functionName ( ...., DataType arrayName[ ] , ... ) { // function body } |
void func( double x[ ] ) { int i; for ( i = 0; i < 30; i++ ) printf( "x[%d] = %lf\n", i, x[i] ); } |
How to run the program:
|
void func( double x[10] ) { int i; for ( i = 0; i < 10; i++ ) printf( "x[%d] = %lf\n", i, x[i] ); } |
|
void func( double* x ) { int i; for ( i = 0; i < 10; i++ ) printf( "x[%d] = %lf\n", i, x[i] ); } |
How to run the program:
|
|
|
|
If you need more details on this phenomenon, please study this CS170 webpage: click here
void func( double x[ ] ) { x[0] = 4444; // WIll change the ORIGINAL !!! x[5] = 4444; } int main( int argc, char* argv[] ) { double a[10]; int i; for ( i = 0; i < 10; i++ ) a[i] = i; printf( "Array before the function call:\n"); for ( i = 0; i < 10; i++ ) printf( "a[%d] = %lf\n", i, a[i] ); func( a ); // Pass array printf( "\nArray AFTER the function call:\n"); for ( i = 0; i < 10; i++ ) printf( "a[%d] = %lf\n", i, a[i] ); } |
Result:
Array before the function call: a[0] = 0.000000 a[1] = 1.000000 a[2] = 2.000000 a[3] = 3.000000 a[4] = 4.000000 a[5] = 5.000000 a[6] = 6.000000 a[7] = 7.000000 a[8] = 8.000000 a[9] = 9.000000 Array AFTER the function call: a[0] = 4444.000000 a[1] = 1.000000 a[2] = 2.000000 a[3] = 3.000000 a[4] = 4.000000 a[5] = 4444.000000 a[6] = 6.000000 a[7] = 7.000000 a[8] = 8.000000 a[9] = 9.000000 |
How to run the program:
|
returnType functionName ( ..., dataType arrayName [ ] [ SIZE ] , ... ) { // function body } |
Example:
void func( double x[ ][5] ) { int i, j; for ( i = 0; i < 3; i++ ) { for ( j = 0; j < 5; j++ ) printf( "x[%d][%d] = %lf ", i, j, x[i][j] ); putchar('\n'); } } int main( int argc, char* argv[] ) { double a[3][5]; int i, j; for ( i = 0; i < 3; i++ ) for ( j = 0; j < 5; j++ ) a[i][j] = i + j; func( a ); } |
How to run the program:
|
|