Academic Program

Pointers and Functions

Passing Pointers to Functions

Normally in C, function parameters are passed by value. This means that if you pass a variable as a parameter to a function, the function makes a copy of that value to operate on and it leaves the original variable alone. As we can see in this example, we pass the variable x to the function squarex is initialized to 2, and is still 2 after the function call. The value of x is copied into n and it is n that is squared and returned from the function to the variable y.

Example

PointersandFunctions.png

 

Passing Parameters By Reference

In many situations, it is desirable to let a function modify the actual variable passed to it. In order to do this, we use a pointer in the function parameter (pass by reference). In order to use a function like this, you need to pass an address or a pointer to the function when it is called. Basically, you are telling the function the address of the variable that you want it to modify.

Example

PassByREference.png

 

A function with a pointer parameter, for example int foo(int *q) must be called in one of two ways:
(assume: int x*p = &x;)

foo(&x) Pass an address to the function so the address
may be assigned to the pointer parameter: q = &x
foo(p) Pass a pointer to the function so the address
may be assigned to the pointer parameter: q = p

Example-Part 1

SwapFunction.png

 

Example-Part 2

MainFunction.png