SE250:HTTB:Pointers:Passing pointers into functions

From Marks Wiki
Jump to navigation Jump to search

<html>

<image src="http://www.rajithaonline.com/SE250/httb/pointers/final/passing_functions_head.png" width="658" height="92" alt="Passing Header Logo" />

</html>

Previous Page Contents Next Page



Passing Pointers Into Functions

There are 2 ways to pass arguments to a function; call-by-value and call-by-reference. But in C, all arguments are passed by value.

Many functions are required to modify the value of one or more of the variables in the caller, or to pass a reference variable(Java terminology) of a rather large data structure and to avoid the cost of using up memory to duplicate this data, C simulates call-by-reference. We do this by using pointers and indirection (referencing a value through a pointer).

  • When calling a function with arguments that need to be modified, the addresses operator(&) needs to be applied to the variable(in the caller)(the variable that has to be modified).

In case for an array, you would notice that when we try to pass in an array to a function, the starting location in memory of the array, and not the array itself, is passed to the function

When the address of a variable is passed to a function, the indirection operator(*) may be used in the function to modify the value at that location in the caller's memory.

Code Example: When passing a pointer into the function, the syntax is:

...
int number = 5;
pointerFunction(&number);
...
...
void pointerFunction(int *nPtr){
  *nPtr = *nPtr * *nPtr * *nPtr;
}
...

A function receiving an address as an argument must define a pointer parameter to receive the address. In the above example, the header specifies that the function is receiving the address of an integer, stores the address locally as nPtr and does not have to return a value.

Caution - Use call-by-value to pass arguments into the function unless the caller requires the called function to modify the value of the argument in the caller environment, to prevent accidental modification

A good idea when passing arrays into a function is also to pass in the size of the array as well, which would make this function reusable.


Previous Page Contents Next Page