Function pointers in C
Let's start with a basic function which we will be pointing to:
int addInt(int n, int m) {
return n+m;
}
First thing, let's define a pointer to a function which receives 2 int
s and returns an int
:
int (*functionPtr)(int,int);
Now we can safely point to our function:
functionPtr = &addInt;
Now that we have a pointer to the function, let's use it:
int sum = (*functionPtr)(2, 3); // sum == 5
Passing the pointer to another function is basically the same:
int add2to3(int (*functionPtr)(int, int)) {
return (*functionPtr)(2, 3);
}
We can use function pointers in return values as well (try to keep up, it gets messy):
// this is a function called functionFactory which receives parameter n
// and returns a pointer to another function which receives two ints
// and it returns another int
int (*functionFactory(int n))(int, int) {
printf("Got parameter %d", n);
int (*functionPtr)(int,int) = &addInt;
return functionPtr;
}
But it's much nicer to use a typedef
:
typedef int (*myFuncDef)(int, int);
// note that the typedef name is indeed myFuncDef
myFuncDef functionFactory(int n) {
printf("Got parameter %d", n);
myFuncDef functionPtr = &addInt;
return functionPtr;
}
Best Answer
getline()
andgetdelim()
to use on machines without a version in the standard library. It used 256 as the minimum allocation (rather than 120) — except when compiled for testing, when it used 8 as the starting point to make sure the reallocation code gets more exercise. The allocated size doubles when there isn't enough room. It was a similar thought process to what the library designers did in the library you use; get the memory allocation big enough first time around that the code mostly won't need to reallocate.)getline()
that tells you how many chars were in the line it just read via its return value. Note that it returns -1 (not EOF) on error. Although it seldom happens, it is theoretically possible for EOF to be a negative value other than -1.You can also rig the system to use shorter lines (until you read a long line) by:
And (for the ultimate in sleazeball programming) you don't even have to error check the allocation since
char *line = NULL;
is also a valid input togetline()
: