Introduction
In C, since the arguments are passed to function by value, there is no direct way for the called function to alter a variable in the calling function. This means the value of variable cannot be changed by calling a function. Instead, a function can only assign a value to a new variable.
Example: Swap
For example, we want swap the value for variable a and b by calling function swap. A simple function could be written like this.
The following interactive element simulates this code. Note that the values do not change after running.
int x = ;
int y = ; swap(x, y); Memory Map Before
Memory Map After
|
Click below to download a copy of the code to run on your own.
|
However, after calling swap, variables a and b have not been changed at all. The reason is that within the function, each variable has its own isolated memory address. This is a "void" function, which means it will return nothing, so after the calling, the variables a, b and temp would disappear. If we want to return an integer, we need make this function the "int" type. This can only return a single value at a time, so we would need multiple functions to return the values of "a" and "b" to "main". However, if we used pointers here, things will get much easier.
By passing a pointer to the function, it can go to the address and change the value directly. This means we don’t need to worry about the isolated memory map.
This is the reason the pointers are needed in functions: it allows direct modification of memory and saves lots of work and time.
By passing a pointer to the function, it can go to the address and change the value directly. This means we don’t need to worry about the isolated memory map.
This is the reason the pointers are needed in functions: it allows direct modification of memory and saves lots of work and time.
int x = ;
int y = ; swap(&x, &y); Memory Map Before
Memory Map After
|
Click below to download a copy of the code to run on your own.
|
Programming Exercise
Write a function to reverse an array of integers using pointers. A prototype is provided below. You can use the above swap function to help.
Reading Quiz
Comments about this page? Please contact us using the link below.
Vertical Divider
|
Want more practice?
Continue to the additional exercises page: Vertical Divider
|
Continue to Advanced Topics:
|