This post was first published on Jupius Learning, where you can read it free with diagrams and practice exercises.
Subscribe to our articles for regular updates.
So far in this series our structs have only held data. A struct can also hold a pointer to a function. Then the struct carries its own behaviour with it, and the code that uses it does not need to know which function it is calling.
This is how C gets something close to objects. It is also one of the most common patterns in the Linux kernel. When you call read() on a file, the kernel does not have a big switch with one case per driver. It follows a pointer from the open file to a table of functions, and calls the read function in that table.
In the last post we put structs inside structs and used container_of to get back to the outer struct. This time we put functions inside structs. We start with a plain function pointer, build up to an "ops table", and then look at struct file_operations in the kernel and how vfs_read calls through f_op->read.
All the sizes in this post come from gcc on a 64-bit x86 Linux machine. I compiled and ran every user-space program shown here.
What is a function pointer in C?
A function has an address, just like a variable. A function pointer is a variable that holds that address. You can call the function through the pointer, and you can point it at a different function later.
#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("op(3, 4) = %d\n", op(3, 4));
op = mul;
printf("op(3, 4) = %d\n", op(3, 4));
printf("sizeof(op) = %zu\n", sizeof(op));
return 0;
}
Save it as fp_basic.c, then compile and run it:
gcc fp_basic.c -o fp_basic
./fp_basic
In PowerShell with MinGW, run it with .\fp_basic.exe.
Output:
op(3, 4) = 7
op(3, 4) = 12
sizeof(op) = 8
The declaration int (*op)(int, int); reads as: op is a pointer to a function that takes two int values and returns an int. The brackets around *op matter. Without them, int *op(int, int); declares a function that returns an int *, which is something else.
op = add; stores the address of add. You do not need &add, because a function name used like this already turns into its address. op(3, 4) calls whatever op points to. The same line gives 7 the first time and 12 the second time.
On x86-64 a function pointer is 8 bytes, the same as any other pointer. That will matter when we put a few of them in a struct.
How do you put a function pointer inside a struct?
You declare it as a field, the same way as in main above. Here is a small struct shape with a width, a height, and a pointer to a function that works out the area.
#include <stdio.h>
struct shape {
const char *name;
double w;
double h;
double (*area)(const struct shape *s);
};
double rect_area(const struct shape *s)
{
return s->w * s->h;
}
double tri_area(const struct shape *s)
{
return 0.5 * s->w * s->h;
}
int main(void)
{
struct shape r = { "rectangle", 4.0, 3.0, rect_area };
struct shape t = { "triangle", 4.0, 3.0, tri_area };
printf("%s area = %.1f\n", r.name, r.area(&r));
printf("%s area = %.1f\n", t.name, t.area(&t));
printf("sizeof(struct shape) = %zu\n", sizeof(struct shape));
return 0;
}
Output:
rectangle area = 12.0
triangle area = 6.0
sizeof(struct shape) = 32
r and t have the same type and the same width and height. They give different answers because each one carries a different area function.
Look at the call r.area(&r). C has no hidden this or self. The function does not know which shape it belongs to, so we pass the shape in as the first argument. The Linux kernel does exactly the same. Almost every function in a kernel ops table takes the object it works on as its first parameter.
The size is 32 bytes: name is a pointer (8), w and h are doubles (8 each), and area is a function pointer (8). Everything is 8 bytes and 8-byte aligned, so there is no padding. If the rules for that are new to you, the padding post covers them.
The function pointer type can get long to read. You can give it a short name with typedef, as we did for structs in the typedef post:
typedef double (*area_fn)(const struct shape *s);
Then the field becomes area_fn area;. Both ways compile to the same thing. The kernel usually writes the full type inside the struct, as you will see in file_operations, so I will do the same here.
From one pointer to an ops table
One function pointer is fine. Real objects usually need more than one, say an area and a perimeter. You could put all of them in struct shape. Then every shape carries every pointer, and you can easily end up with a rectangle whose area is the square version by mistake.
The kernel does something tidier. It puts all the functions for one kind of object into a separate struct, an "ops table". Each object then holds just one pointer to its table.
#include <stdio.h>
struct shape;
struct shape_ops {
double (*area)(const struct shape *s);
double (*perimeter)(const struct shape *s);
void (*describe)(const struct shape *s);
};
struct shape {
const char *name;
double w;
double h;
const struct shape_ops *ops;
};
static double rect_area(const struct shape *s) { return s->w * s->h; }
static double rect_perim(const struct shape *s) { return 2 * (s->w + s->h); }
static void rect_describe(const struct shape *s)
{
printf("%s, %.1f by %.1f\n", s->name, s->w, s->h);
}
static double square_area(const struct shape *s) { return s->w * s->w; }
static double square_perim(const struct shape *s) { return 4 * s->w; }
static const struct shape_ops rect_ops = {
.area = rect_area,
.perimeter = rect_perim,
.describe = rect_describe,
};
static const struct shape_ops square_ops = {
.area = square_area,
.perimeter = square_perim,
/* no .describe, so it is NULL */
};
static void show(const struct shape *s)
{
if (s->ops->describe)
s->ops->describe(s);
else
printf("%s (no describe function)\n", s->name);
printf(" area = %.1f, perimeter = %.1f\n",
s->ops->area(s), s->ops->perimeter(s));
}
int main(void)
{
struct shape a = { .name = "door", .w = 2.0, .h = 1.0, .ops = &rect_ops };
struct shape b = { .name = "table", .w = 3.0, .h = 1.5, .ops = &rect_ops };
struct shape c = { .name = "tile", .w = 3.0, .ops = &square_ops };
show(&a);
show(&b);
show(&c);
printf("sizeof(struct shape_ops) = %zu\n", sizeof(struct shape_ops));
printf("sizeof(struct shape) = %zu\n", sizeof(struct shape));
printf("a and b share one table: %s\n", a.ops == b.ops ? "yes" : "no");
return 0;
}
Output:
door, 2.0 by 1.0
area = 2.0, perimeter = 6.0
table, 3.0 by 1.5
area = 4.5, perimeter = 9.0
tile (no describe function)
area = 9.0, perimeter = 12.0
sizeof(struct shape_ops) = 24
sizeof(struct shape) = 32
a and b share one table: yes
A few things are going on here.
rect_ops and square_ops are filled with designated initializers, .area = rect_area and so on. We used the same syntax for nested structs in the last post. You name each field, so the order does not matter, and any field you leave out is set to zero. For a pointer, zero means NULL. square_ops has no .describe, so its describe field is NULL.
The tables are static const. There is one copy of each, it never changes while the program runs, and the compiler can put it in read-only memory. The door and the table both point at the same rect_ops. That is what the last line of the output shows.
The show function never mentions rectangles or squares. It only knows about s->ops. If you add a circle later, you write the circle functions and a circle_ops table, and show does not change at all.
Look at the size too. struct shape is still 32 bytes, because it holds one pointer to the table instead of three function pointers. With all three pointers stored directly in each shape, I measured 48 bytes. That is 16 bytes saved for every shape. A busy kernel can keep a very large number of inodes and open files in memory, so the saving adds up there.
struct shape; at the top is a forward declaration. struct shape_ops needs to mention struct shape in its function types before struct shape is fully declared. A pointer to an incomplete struct is allowed, so one line is enough to break the circle.
Why check for NULL before calling?
show checks s->ops->describe before calling it. That is not decoration. Calling a NULL function pointer crashes the program.
#include <stdio.h>
struct ops {
void (*hello)(void);
void (*bye)(void);
};
static void say_hello(void) { printf("hello\n"); }
static const struct ops my_ops = {
.hello = say_hello,
};
int main(void)
{
printf("bye is %s\n", my_ops.bye == NULL ? "NULL" : "set");
my_ops.hello();
my_ops.bye(); /* no check: this crashes */
printf("never printed\n");
return 0;
}
Run in a terminal, the output is:
bye is NULL
hello
Segmentation fault
The bye field was never set, so the designated initializer made it NULL. Calling it jumps to address 0, and the operating system stops the program. In the Linux kernel the same mistake is an oops, a kernel crash report, and it can take the whole machine down.
So there is a simple rule with ops tables. If a function is optional, check it before you call it. If a function is required, make sure every table sets it. You will see the kernel do both.
Choosing behaviour at runtime
So far each object got its table when we wrote the code. The table can also be chosen while the program runs, from user input or from the name of a device. Here is a small program that picks a text conversion by name from the command line.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
struct text_ops {
const char *name;
void (*convert)(char *s);
};
static void to_upper(char *s)
{
for (; *s; s++)
*s = (char)toupper((unsigned char)*s);
}
static void to_lower(char *s)
{
for (; *s; s++)
*s = (char)tolower((unsigned char)*s);
}
static void reverse(char *s)
{
size_t i, n = strlen(s);
for (i = 0; i < n / 2; i++) {
char c = s[i];
s[i] = s[n - 1 - i];
s[n - 1 - i] = c;
}
}
static const struct text_ops all_ops[] = {
{ .name = "upper", .convert = to_upper },
{ .name = "lower", .convert = to_lower },
{ .name = "reverse", .convert = reverse },
};
static const struct text_ops *find_ops(const char *name)
{
size_t i;
for (i = 0; i < sizeof all_ops / sizeof all_ops[0]; i++)
if (strcmp(all_ops[i].name, name) == 0)
return &all_ops[i];
return NULL;
}
int main(int argc, char *argv[])
{
char text[] = "Hello Kernel";
const struct text_ops *ops;
if (argc < 2) {
printf("usage: %s upper|lower|reverse\n", argv[0]);
return 1;
}
ops = find_ops(argv[1]);
if (ops == NULL) {
printf("unknown mode: %s\n", argv[1]);
return 1;
}
ops->convert(text);
printf("%s: %s\n", ops->name, text);
return 0;
}
Compile it once:
gcc pick_ops.c -o pick_ops
Then run it with different arguments:
./pick_ops upper
./pick_ops reverse
./pick_ops shout
Output:
upper: HELLO KERNEL
reverse: lenreK olleH
unknown mode: shout
all_ops is an array of structs, each with a name and a function pointer. find_ops walks the array and returns a pointer to the matching entry, or NULL if there is none. After that, main only calls ops->convert(text). It has no if for upper and another for lower.
Notice the NULL check again, this time on the table pointer itself. If the name is unknown there is no table, and calling ops->convert would crash.
This is close to what the kernel does when you open a device file. It looks up which driver owns that device, takes that driver's table of functions, and stores a pointer to it in the open file. Every later call on that file goes through that pointer.
Read the rest on Jupius
That covers how to declare a function pointer, how to put it in a struct, how to share one ops table between many objects, and why every optional call needs a NULL check. The second half of the post moves into the Linux kernel. It walks through struct file_operations, a small /dev/hello driver filled with designated initializers, and how vfs_read calls the driver through file->f_op. It ends with the same pattern in inode_operations and super_operations.
Read the full post on Jupius Learning. It is free, with every example, the diagrams and the practice exercises.
If you want to practice structs with small exercises that check your code as you go, the C programming course at Jupius Learning covers them step by step.

Top comments (0)