C Pointers and Functions
Pointers and functions work together in three ways.
1. Pass a pointer to change values
#include <stdio.h>
void increase(int *n) {
*n = *n + 10;
}
int main(void) {
int x = 5;
increase(&x);
printf("%d\n", x);
return 0;
}
Output:
Output of the above program is
15
2. Get more than one value from a function
A function can return only one value, but with pointers it can fill many variables.
#include <stdio.h>
void minMax(int a[], int n, int *min, int *max) {
*min = *max = a[0];
for (int i = 1; i < n; i++) {
if (a[i] < *min) *min = a[i];
if (a[i] > *max) *max = a[i];
}
}
int main(void) {
int marks[] = {45, 90, 33, 78};
int lo, hi;
minMax(marks, 4, &lo, &hi);
printf("Min = %d, Max = %d\n", lo, hi);
return 0;
}
Output:
Output of the above program is
Min = 33, Max = 90
3. Function that returns a pointer
Never return the address of a normal local variable. It is removed when the function ends. Return an address of a static, global or dynamic memory.
#include <stdio.h>
int *bigger(int *a, int *b) {
return (*a > *b) ? a : b;
}
int main(void) {
int x = 8, y = 15;
int *p = bigger(&x, &y);
printf("%d\n", *p);
return 0;
}
Output:
Output of the above program is
15
Function pointer
A pointer can also store the address of a function. Then you can call the function through it.
#include <stdio.h>
int add(int a, int b) { return a + b; }
int mul(int a, int b) { return a * b; }
int main(void) {
int (*op)(int, int);
op = add;
printf("%d\n", op(3, 4));
op = mul;
printf("%d\n", op(3, 4));
return 0;
}
Output:
Output of the above program is
7
12
Note:
Function pointers are used for callbacks, for example, the compare function of qsort().
Next: C Dynamic Memory Allocation.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |