|
|
Example:
int main(int argc, char *argv[])
{
int x1 = 4, x2 = 88;
func( &x1 ); // Pass address of x1 to function
func( &x2 ); // Pass address of x2 to function
}
|
Explanation:
|
func( &x );
|
Question:
|
int a = 7; // an int typed variable
// &a = the address of a int typed variable
int *p; // p can hold an address of an int typed variable
// Therefore: p can store &a !!!
p = &a; // Store the address of the int type variable a in p
|
So we must use:
int *varName
|
as parameter type !!!
#include <stdio.h>
void func( int *p )
{
printf( " p = %u\n", p ); // Print the parameter p
// We SHOULD use %p (hex), but I like %u (dec)
// I will get a warning and I can live with it
printf( "*p = %d\n\n", *p ); // Print the variable pointed to by p
}
int main(int argc, char *argv[])
{
int x1 = 4, x2 = 88;
func( &x1 ); // Pass address of x1 to function
func( &x2 ); // Pass address of x2 to function
}
|
The output of this program is:
cs255-1@aruba (5572)> a.out p = 3731491632 *p = 4 p = 3731491636 *p = 88 |
You can see that the function func( ) can access the original variables through the reference (= address) passed by &x and &y !!!
I do so by:
|
#include <stdio.h>
void func( int *p )
{
// The expression *p will access the ORIGINAL variable !!
*p = *p + 1; // Add 1 to the (original) variable
}
int main(int argc, char *argv[])
{
int x1 = 4, x2 = 88;
printf("x1 before = %d\n", x1);
func( &x1 ); // Pass address of x1 to function
printf("x1 after = %d\n", x1);
printf("x2 before = %d\n", x2);
func( &x2 ); // Pass address of x2 to function
printf("x2 after = %d\n", x2);
}
|
Output of this program:
cs255-1@aruba (5577)> a.out x1 before = 4 x1 after = 5 x2 before = 88 x2 after = 89 |
So you can see that the parameter was passed by reference !!!
How to run the program:
|
|