Pointers To Functions In C C Language

Jul 16th, 2021 - written by Kimserey with .

Last week we covered the basics of C pointers with their definitions and how to use them in variables and functions. In today’s post we will look at pointers to function and more specificities around pointers like NULL pointer or void return.

Pointers to Functions

Pointers to functions in C can be declared as such:

1
int (*comp)(int *, int *)

The declaration (*comp) identifies a pointer to a function, where (int *, int *) are the arguments taken by the function and int the return type.

From here we can test assign to it a function, for example if we have an addition:

1
2
3
4
int add(int *a, int *b)
{
    return *a + *b;
}

We are able to assign it to comp:

1
2
3
4
5
6
7
int (*hello)(int *, int *) = add;

int a = 3;
int b = 3;
int res = hello(&a, &b);

printf("%d", res);

This becomes useful when used as parameter of function. For example, we could have a function which perform some operation and while requiring comparison function. In this case, we might want to let the user of the function to define the logic of the comparaison.

1
void sort(void *v[], int (*comp)(void *, void*));

This definition of sort is made generic by using a pointer to void for the array allowing the user to provide any type of array. And the comparison will take pointers to void allowing the argument of the comparison comp to be of the same type of the array.

This allows us to implement the logic of sort without tying it to any specific type.

Pointers to Struct

Pointers to structs work just like other pointers. The only added difference is the arrow notation -> which can be used to access a property of the dereferenced pointer.

It is a shorthand to access the properties of the struct. For example:

1
2
3
4
5
typedef struct point
{
    int x;
    int y;
} MyPoint;
1
2
3
MyPoint a = {1, 2};
MyPoint *b = &a;
printf("%d - %d", (*b).x, b->x);

we can see that(*b).x is equivalent to b->x.

NULL Pointer and void return

Lastly, we saw earlier that using void type allowed us to define pointers not associated to any data type. This allowed us to make generic functions.

1
void sort(void *v[], int (*comp)(void *, void*));

Another specificity of pointers is the NULL pointer. NULL is a value that can be set on any pointer:

1
2
3
int *a = NULL;
char *b = NULL;
struct myStruct *c = NULL;

It can be used to initialise a pointer and make comparison.

And that concludes today’s post!

Conclusion

Today we continued our discovery of C pointers where we looked at the definition of pointer to function, and the shorthand notation for accessing properties of pointer to struct. We then completed the post by discussing void data type and NULL pointers. I hope you liked this post and I see you on the next one!

External Sources

Designed, built and maintained by Kimserey Lam.