Programs & Examples
Pointers · Study material
Pointer to a structure and the -> operator
Pass large structures by address so the function can change them without copying. s->marks is shorthand for (*s).marks.
#include <stdio.h>
struct student {
char name[20];
int marks;
};
void add_bonus(struct student *s, int bonus) {
s->marks += bonus; /* same as (*s).marks += bonus */
}
int main(void) {
struct student s = {"Asha", 78};
add_bonus(&s, 5);
printf("%s scored %d\n", s.name, s.marks);
return 0;
}
Asha scored 83
Array of function pointers (calculator)
Function pointers let you choose behaviour at run time – a menu, a callback or a sort comparator such as the one qsort() takes.
#include <stdio.h>
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int mul(int a, int b) { return a * b; }
int main(void) {
int (*ops[])(int, int) = {add, sub, mul}; /* array of function pointers */
const char *names[] = {"add", "sub", "mul"};
for (int i = 0; i < 3; i++)
printf("%s(12, 4) = %d\n", names[i], ops[i](12, 4));
return 0;
}
add(12, 4) = 16 sub(12, 4) = 8 mul(12, 4) = 48
Dynamic array with malloc and realloc
Allocate memory at run time, grow it with realloc(), and keep the old pointer until realloc() succeeds so nothing leaks.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n = 3;
int *a = malloc(n * sizeof *a);
if (a == NULL)
return 1;
for (int i = 0; i < n; i++)
a[i] = (i + 1) * 10;
int *bigger = realloc(a, 5 * sizeof *a); /* grow to 5 elements */
if (bigger == NULL) {
free(a);
return 1;
}
a = bigger;
a[3] = 40;
a[4] = 50;
for (int i = 0; i < 5; i++)
printf("%d ", a[i]);
printf("\n");
free(a);
return 0;
}
10 20 30 40 50
Generic swap with void pointers
A void * accepts any address. With the size of the type, one function can swap ints, doubles or structures – the idea behind memcpy() and qsort().
#include <stdio.h>
#include <string.h>
void swap_any(void *x, void *y, size_t size) {
unsigned char tmp[64]; /* enough for the small types used here */
memcpy(tmp, x, size);
memcpy(x, y, size);
memcpy(y, tmp, size);
}
int main(void) {
int a = 1, b = 2;
double c = 1.5, d = 9.25;
swap_any(&a, &b, sizeof a);
swap_any(&c, &d, sizeof c);
printf("a = %d, b = %d\n", a, b);
printf("c = %.2f, d = %.2f\n", c, d);
return 0;
}
a = 2, b = 1 c = 9.25, d = 1.50
Passing a 2D array with a pointer to a row
A 2D array decays to a pointer to its first row, here int (*)[3]. The column count must be known to the function.
#include <stdio.h>
void print_matrix(int rows, int (*m)[3]) { /* m points to a row of 3 ints */
for (int r = 0; r < rows; r++) {
for (int c = 0; c < 3; c++)
printf("%3d", m[r][c]);
printf("\n");
}
}
int main(void) {
int m[2][3] = {{1, 2, 3}, {4, 5, 6}};
print_matrix(2, m);
return 0;
}
1 2 3 4 5 6