Using Pointers for Variable Parameters
Most C programmers first need to use pointers for variable parameters. Suppose you have a simple procedure in Pascal that swaps two integer values:
Because this code uses variable parameters, it swaps the values a and b correctly.
C has no formal mechanism for passing variable parameters: It passes everything by value. Enter and execute the following code and see what happens:
No swapping takes place. The values of a and b are passed to swap, but no values are returned.
To make this function work correctly, you must use pointers, as shown below:
To get an idea of what this code does, print it out, draw the two integers a and b, and enter 5 and 10 in them. Now draw the two pointers i and j, along with the integer t. When swap is called, it is passed the addresses of a and b. Thus, i points to a (draw an arrow from i to a) and j points to b (draw another arrow from b to j). Because the pointers have been established, *i is another name for a, and *j is another name for b. Now run the code in swap. When the code uses *i and *j, it really means a and b. When the function completes, a and b have been swapped.
Suppose you accidentally forget the & when the swap function is called, and that the swap line accidentally looks like this: swap(a,b);. This causes a segmentation fault. When you leave out the &, the value of a is passed instead of its address. Therefore, i points to an invalid location in memory and the system crashes when *i is used.
This is also why scanf crashes if you forget &--- scanf is using pointers to put the value it reads back into the variable you have passed. Without &, scanf is pas
|