Lesson 37: Pointers Part 4: Pointers and Functions
Using pointers in functions enables us to perform Call by Reference and pass complex data structures efficiently.
1. Achieving Call by Reference (The Swap Function)
To allow a function to modify variables declared outside its scope, we pass the addresses of those variables.
c #include <stdio.h>
void swap(int *x, int *y) { int temp = *x; // Store the value pointed to by x *x = *y; // Change the value at address x to the value at address y *y = temp; // Change the value at address y to the original x value }
int main() { int a = 5, b = 10; printf("Before swap: a=%d, b=%d\n", a, b);
// Pass the addresses
swap(&a, &b);
printf("After swap: a=%d, b=%d\n", a, b);
return 0;
}
2. Returning Pointers from Functions
Functions can return a pointer (an address).
Warning: Never return the address of a local (automatic) variable, as that memory is deallocated when the function exits, resulting in a dangling pointer.
If you must return a pointer, it should point to:
- A global variable.
- A static local variable.
- Dynamically allocated memory (covered next).
- Memory passed into the function as an argument.