You can pass pointers as arguments to functions.
- This allows the function to directly access and modify the variable whose address is passed.
- Passing pointers enables call-by-reference behavior in C.
Why Use?
- To modify the actual value of a variable inside a function.
- To pass large arrays or data efficiently without copying.
- To return multiple values using pointers.
Example:
#include <stdio.h>
// Function to swap two integers using pointers
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 10, y = 20;
printf("Before swap: x = %d, y = %d\n", x, y);
swap(&x, &y); // Passing addresses of x and y
printf("After swap: x = %d, y = %d\n", x, y);
return 0;
}Function Returning Pointers
Functions can return pointers.
- This is useful when the function needs to return the address of a variable or array.
- Important: The pointer returned must point to valid memory (not to a local variable inside the function, which goes out of scope).
Example: Returning pointer to array
#include <stdio.h>
int* getArray() {
static int arr[3] = {1, 2, 3}; // static so it persists after function ends
return arr; // return address of first element
}
int main() {
int *ptr = getArray();
for (int i = 0; i < 3; i++) {
printf("%d ", ptr[i]);
}
printf("\n");
return 0;
}
Discussion 0