Passing Addresses to Functions

Now that you have a basic understanding of addresses (albeit thanks to trivial examples), it's time to look at some tasks that cannot be solved without using addresses. The remaining examples will show how useful pointers are.

In this next example, pointers to variables that exist in the main function will be passed to another function. Why is this useful? Consider this example: you want to create a function that swaps the values of two variables. You might be tempted to try a program like Script 9.5.

Script 9.5. Because the swap() function works on copies of the original values, it cannot affect the values of the actual variables defined in the main program.


The problem is that such an application will not work because what the main function passes to the swap() function are the values of the variables a and b, not the variables themselves. The variables first and second that the swap() function manipulates are local to that function. Changes to such local variables are not visible in the main function, as the program's output would show (Figure 9.11).

Figure 9.11. The swap() function could not change the value of main's variables because it only affected the local variable values.


To get the desired effect, we need to pass the addresses of the variables in the main program to the swap function, as the next example demonstrates.

To pass addresses to a function

1.
Create a new file or project in your text editor or IDE.

2.
Type the standard beginning lines of code (Script 9.6):

/* pointer6.c - Script 9.6 */
#include <stdio.h>

Script 9.6. In this version of the application, the swap() function is given the addresses of the variables from the main program and can therefore change their associated values.


3.
Add the function prototype for the swap function:

void swap(int *first, int *second);

The prototype declares that the function takes two parameters, both of which are addresses of integer variables (pointers to int). Note that these asterisks indicate pointer variables; they are not being used as dereferencing operators.

4.
Begin the main function;

int main (void) {

5.
Define and initialize two integer variables, then print their values:

int a = 5, b = 10;
printf("At first, a = %d, b = %d.
",
 a, b);

This application will swap the two variable values. To demonstrate this in action, their original values are first printed.

6.
Call the swap function, passing it the addresses of the two variables:

swap(&a, &b);

Instead of passing the swap() function two values, as in

swap (a, b);

the swap function will now receive the address of the two variables. This will allow that function to access and alter these variables' values.

7.
Print the variables' values again:

printf("After swapping, a = %d,
 b = %d.
", a, b);

After calling the swap function, the variables' values are printed again to confirm that a swap was made.

8.
Complete the main function:

    getchar();
    return 0;
}

9.
Begin the swap function definition:

void swap(int *first, int *second) {

The function expects to receive two addresses of integer variables as parameters. These addresses will be made available to the function's code in the two pointer variables—first and second—declared here.

10.
Define a local integer variable temp and initialize it with the value stored at the first integer address:

int temp = *first;

As you have already learned, we use the dereferencing operator * to get the value when you have an address.

11.
Exchange the two values, again using the dereferencing operators:

*first = *second;
*second = temp;

The important point here is that the function is actually changing the values of the variables a and b in the main program. This is possible because the two pointer variables first and second contain the addresses of a and b. By dereferencing first and second to work with the values, changing *first is equivalent to changing a and changing *second is equivalent to changing b.

Revisiting the scanf() Function

Only the use of pointers makes the ability to change a variable's value in another function possible. You have already seen this concept, though, with standard library functions like scanf().

scanf() assigns to variables values parsed from a source, using a formatting pattern to make that association. For example, this code reads in two integers (separated by a space) from the standard input and assigns them to variables:

int num1, num2;
scanf("%d %d", &num1, &num2);

The scanf() function cannot return more than a single value (a limitation on all functions), so it must find another way to assign values to variables.

What happens instead is that you pass scanf() the addresses of all these variables (like &num1 and &num2). Since scanf() can dereference the addresses using the * operator, it is able to assign the variables values it has parsed out of the input.

Again, without pointers, there would be no way for a function like scanf() to do its job.


12.
Complete the swap function:

}

13.
Save the file as pointer6.c, compile, and debug as necessary.

14.
Run the application (Figure 9.12).

Figure 9.12. This version of the swap() function was able to change the variables in the main function because it was given their addresses instead of their values.


This time, the changes performed in the swap() function had the desired effect in the main program.

✓ Tips

  • In this chapter, pointers are only used on regular variables. You can also use pointers to pointer variables. This would again allow you to pass the address of a pointer variable to a subroutine and have the subroutine fill your pointer variable with an address. Such techniques are beyond the scope of this book, though.

  • To reacquaint yourself with variable scope, turn to the end of Chapter 7, “Creating Your Own Functions.”


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset