Thank you for taking the time to read this, I looked for answers before posting but I'm very new to the language. This exercise I'm trying to do is from the book "Effective C: An introduction to professional C programming".
This is my first go at learning the language, and the exercise from the 2nd chapter of the book is as follows:
Declare an array of three pointers to functions and invoke the appropriate function based on an index value passed in as an argument
I am not totally sure I understand what it's saying, but I have a piece of functioning code I think does the job. However, I'm not sure if I'm interpreting it correctly. Here's my code:
#include <stdio.h>
#include <stdlib.h>
void f0(int x) {
printf("I am f0 and in index location %d\n", x);
}
void f1(int x) {
printf("I am f1 and in index location %d\n", x);
}
void f2(int x) {
printf("I am f2 and in index location %d\n", x);
}
int main(void){
void (*f0p)(int);
f0p = &f0;
void (*f1p)(int);
f1p = &f1;
void (*f2p)(int);
f2p = &f2;
void *array[3] = {f0p, f1p, f2p};
for (int i = 0; i < 3; i++) {
void (*program)(int);
program = array[i];
program(i);
}
return 0;
}
this works after compiling and returns the following:
I am f0 and in index location 0
I am f1 and in index location 1
I am f2 and in index location 2
However, am I completing the exercise correctly? I don't think I'm technically using the index as an argument and calling the function, but I'm a noob. Any validation or correction / education you provide would be extremely appreciated. I spent many hours on this today!
Pointers should not be converted between pointers-to-functions and pointers-to-objects (including void
) except in special situations.
The array is better declared as an array of pointers to functions:
void (*arrray[])(int) = { f0, f1, f2 };
and the functions can be called without an intermediate variable:
array[i](i);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments