



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
A detailed explanation of C function pointers, including their declaration, usage, and an example of an array of function pointers. Students of computer science, particularly those studying programming languages, will find this document useful for understanding the concept of function pointers in C programming.
What you will learn
Typology: Lecture notes
1 / 6
This page cannot be seen from the preview
Don't miss anything!
#include <stdio.h> int addi (int x, int y) { return x+y; } int subi (int x, int y) { return x-y; } int useFunctionPtr ( int a, int b, int (* fun ) (int, int)) { return fun(a, b); } int main () { int x = 3, y = 5, result; result = useFunctionPtr (x, y, &addi); printf("%d + %d = %d\n", x, y, result); result = useFunctionPtr (x, y, &subi); printf("%d - %d = %d\n", x, y, result);
#include <stdio.h> #include <stdlib.h> int addi (int x, int y) { return x+y; } int subi (int x, int y) { return x-y; } int main () { int x, y, result; char op; int (func) (int, int); printf("Enter int op int, no blanks (e.g., 3+144)"); scanf("%d%c%d", &x, &op, &y); printf("You entered %d %c %d\n", x, op, y); if (op == '+') func = &addi; else if (op == '-') func = &subi; else exit(1); result = (func)(x, y); printf("%d %c %d= %d\n", x, op, y, result);
#include <stdio.h> int addi(int x, int y) { return x+y; } int subi(int x, int y) { return x-y; } int main () { int i, x, y, result; char op; int (funcArr[2]) (int, int); // an array of function ptrs funcArr[0] = &addi; funcArr[1] = &subi; int dataArr[4][2] = { {1, 10}, {2, 20}, {3, 30}, {4, 40}}; for (i=0; i<4; i++) { x = dataArr[i][0]; y = dataArr[i][1]; op = (i%2)? '-' : '+'; result = (funcArr[i%2])(x, y); printf("%d %c %d = %d\n", x, op, y, result); }