|
|
Example:
int main(int argc, char *argv[]) { double x1 = 4, x2 = 88; func( &x1 ); // Pass address of x1 to p func( &x2 ); // Pass address of x2 to p } |
Explanation:
|
func( &x ); |
|
void func( double *p ) { printf( " p = %u\n, p ); // Print the parameter p printf( "*p = %lf\n, *p ); // Print the variable pointed to by p } |
Explanation:
|
|
Output of this program:
Value of &x1 = 4290769472 Value of x1 = 4.000000 p = 4290769472 *p = 4.000000 Value of &x2 = 4290769464 Value of x2 = 88.000000 p = 4290769464 *p = 88.000000 |
How to run the program:
|
|
|
Example:
BankAccount x = new BankAccount(); BankAccount y; y = x; // y is now an alias for x |
double x1; double *p; p = &x1; // *p is now an alias for x1 |
|
void update( double a ) // a is passed by value { printf( "Inside update - before changing a, a = %lf\n", a); a = a + 1; // Cannot update a in main !!! printf( "Inside update - AFTER changing a, a = %lf\n", a); } int main( int argc, char* argv[] ) { double a = 3.14; printf( "Inside main - before calling update(a), a = %lf\n", a); update ( a ); // a is passed by value !!! printf( "Inside main - AFTER calling update(a), a = %lf\n", a); } |
Result:
Inside main - before calling update(a), a = 3.140000 Inside update - before changing a, a = 3.140000 Inside update - AFTER changing a, a = 4.140000 Inside main - AFTER calling update(a), a = 3.140000 Unchanged !!! |
How to run the program:
|
|
|
void update( double *a ) // 1. Use a reference parameter variable { // Important: // a = address of the actual parameter variable // *a = an alias of the actual parameter variable !!! printf( "Inside update - before changing *a, *a = %lf\n", *a); *a = *a + 1; // We CAN update a in main !!! printf( "Inside update - AFTER changing *a, *a = %lf\n", *a); } int main( int argc, char* argv[] ) { double a = 3.14; printf( "Inside main - before calling update(a), a = %lf\n", a); update ( &a ); // pass the reference to a !!! printf( "Inside main - AFTER calling update(a), a = %lf\n", a); } |
Result:
Inside main - before calling update(a), a = 3.140000 Inside update - before changing *a, *a = 3.140000 Inside update - AFTER changing *a, *a = 4.140000 Inside main - AFTER calling update(a), a = 4.140000 (Changed !!!) |
How to run the program:
|
|