pointer to function?

B

Bill Cunningham

I having been studying struct here lately and have come across pointers
to functions. Can someone explain to me a scenario where a pointer to a
function would be used and where this versatility would be needed.

int (*pf) function (int,int);

Thanks.
 
K

Keith Thompson

Bill Cunningham said:
I having been studying struct here lately and have come across pointers
to functions. Can someone explain to me a scenario where a pointer to a
function would be used and where this versatility would be needed.

int (*pf) function (int,int);

It's extremely unlikely that any answers you get here will be better
than what you can read in a decent book. You have K&R2, right?
 
B

Bill Cunningham

It's extremely unlikely that any answers you get here will be better
than what you can read in a decent book. You have K&R2, right?
You bet. I just wanted to draw on experience from someone who has used
this technique. I thought I might learn something.

Bill
 
R

Richard

Bill Cunningham said:
You bet. I just wanted to draw on experience from someone who has used
this technique. I thought I might learn something.

Bill

Consider an API function along the lines of

sendEmail(struct HEADER * h, struct MSG * );

Now, code from all over the system can call this for a specific user.

But that user has his own configuration for HOW the message is sent. The
only thing that remains constant are the Header and the Msg
structures. What they contain is immaterial at this stage.

Now, there is a concept of currentUser() which returns something
identifying the current user.

Consider something rough like this:

,----
| #include <stdio.h>
|
| struct HEADER {
| int h;
| };
|
| struct MSG {
| int m;
| };
|
| int currentUser(){
| return 0;
| }
|
| int sendFunctionIMAP(struct HEADER * h, struct MSG *m){
| return -1;
| }
|
| int (*getSendFunction(int i,struct HEADER *h, struct MSG *m))(struct HEADER *h, struct MSG *m)
| {
| return &sendFunctionIMAP;
| }
|
|
|
| int sendEmail(struct HEADER * h, struct MSG * m)
| {
| int (*sendFunctionPtr)(struct HEADER *, struct MSG *);
| int rc;
|
| if ((sendFunctionPtr = getSendFunction(currentUser(),h,m)) != NULL){
| if ((rc=(*sendFunctionPtr)(h,m))!=0){
| /* report error */
| }
| }
|
| return rc;
|
| }
|
| int main(int argc, char ** argv) {
|
| struct HEADER h;
| struct MSG m;
|
| /* set up structs */
|
| sendEmail(&h,&m);
|
| }
`----

Think about it.
 
B

Ben Bacarisse

Bill Cunningham said:
I having been studying struct here lately and have come across pointers
to functions. Can someone explain to me a scenario where a pointer to a
function would be used and where this versatility would be needed.

One of the most common uses occurs when you need to tell a function
something that can best be described by writing code. The classic
example is C's qsort function. The last parameter is a pointer to a
function that qsort uses to determine how one item on the array
compares to an other.

Try writing a general sorting function that has to be told how to sort
via plain data parameters (i.e. without using a function pointer) and
you will so how much the technique is worth.
int (*pf) function (int,int);

If that line is from a tutorial, consider ditching it, since it is
almost certainly wrong.
 
J

John Bode

    I having been studying struct here lately and have come across pointers
to functions. Can someone explain to me a scenario where a pointer to a
function would be used and where this versatility would be needed.

int (*pf) function (int,int);

Thanks.

I once worked on a system that had to process a number of files
generated by several Labview-driven instruments. Each instrument
generated two types of files: a calibration file and a data file, each
of which had to be treated differently.

So I wrote up a bunch of parsing and loading functions, then built a
lookup table of function pointers keyed by instrument and file type:

/**
* Lookup table type
*/
struct lut {
char *instrument;
char *extension;
int (*parser)(FILE *stream);
};

/**
* Parse function implementations
*/
int parseMSTData (FILE *stream) { /* parse MST data file */ }
int parseMSTCal (FILE *stream) { /* parse MST calibration file */ }
int parseGRAData (FILE *stream) { /* parse GRAPE data file */ }
int parseGRACal (FILE *stream) { /* parse GRAPE calibration data */ }

/**
* Lookup table data
*/
struct lut parserLookup[] =
{"MST", "DAT", parseMSTData},
{"MST", "CAL", parseMSTCal},
{"GRA", "DAT", parseGRAData},
{"GRA", "CAL", parseGRACal},
};

/**
* Main loop
*/
void ParseAllFiles(char **fileNames)
{
while (*fileNames)
{
char instrument[4], type[4];
int (*parser)(FILE *stream);
FILE *stream;

/**
* GetParser extracts the instrument and file
* type based on the file name, then retrieves
* the pointer to the right function from the
* lookup table; returns NULL if no matching
* function is found.
*/
parser = GetParser(char *fname);
if (parser)
{
FILE *stream = fopen (*fileNames, "r");
if (stream)
{
if (parser(stream))
/* load data */
fclose(stream);
}
}
fileNames++;
}
}

This allowed me to add new functions as new instruments came on line
without having to change the main processing code; all I had to do was
update the lookup table as I added new functions.
 
U

user923005

    I having been studying struct here lately and have come across pointers
to functions. Can someone explain to me a scenario where a pointer to a
function would be used and where this versatility would be needed.

int (*pf) function (int,int);

Consider a sorting function.
You might pass it an array of ints.
You might pass it an array of doubles.
You might pass it an array of char pointers.
You might pass it an array of struct airplanes.
How will your sort function know which objects are larger than their
neighbors?
Via a compare function.
You pass the function pointer to the sorting function as one of its
arguments.
See, for example:
http://www.dinkumware.com/manuals/default.aspx?manual=compleat&page=stdlib.html#qsort
 
L

lovecreatesbeauty

    I having been studying struct here lately and have come across pointers
to functions. Can someone explain to me a scenario where a pointer to a
function would be used and where this versatility would be needed.

int (*pf) function (int,int);

It's been used in the standard library somewhere like these. Think
about these standard usage.

#include <signal.h>
void (*signal(int sig, void (*func)(int)))(int);

#include <stdlib.h>
void *bsearch(const void *key, const void *base,
size_t nmemb, size_t size,
int (*compar)(const void *, const void *));

void qsort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
 
M

Moi

I having been studying struct here lately and have come across pointers
to functions. Can someone explain to me a scenario where a pointer to a
function would be used and where this versatility would be needed.

int (*pf) function (int,int);

Thanks.

#include <stdlib.h>

typedef double dick;

struct llist {
struct llist *next;
char payload[sizeof (dick)];
};

int llist_cmp(struct llist *one, struct llist *two)
{
return (rand() %2) ? -1 : 1;
}

struct llist * llist_merge(struct llist *one, struct llist *two
, int (*cmp)(struct llist *l, struct llist *r))
{
struct llist *new = NULL;
struct llist **hnd = &new;

while (one && two) {
if (cmp(one,two) >= 0) {
*hnd = one; hnd = &one->next; one = one->next; }
else {
*hnd = two; hnd = &two->next; two = two->next; }
}
*hnd = (one) ? one: two;
return new;
}

HTH,
AvK
 
R

Richard

It's been used in the standard library somewhere like these. Think
about these standard usage.

#include <signal.h>
void (*signal(int sig, void (*func)(int)))(int);

#include <stdlib.h>
void *bsearch(const void *key, const void *base,
size_t nmemb, size_t size,
int (*compar)(const void *, const void *));

void qsort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));

In my experience, and as a result of the "got to get my name up" culture
of this group, c.l.c is the only usenet group where people never see other
peoples posts. Why is that? I know we've heard from liars that it takes
"days" or "hours" for news posts to "propagate" to them. I don't believe
it. If this was 1975 then maybe.

I purposely posted a more convoluted explanation knowing about a million
people would come running out with qsort.
 
L

lovecreatesbeauty

In my experience, and as a result of the "got to get my name up" culture
of this group, c.l.c is the only usenet group where people never see other
peoples posts. Why is that? I know we've heard from liars that it takes
"days" or "hours" for news posts to "propagate" to them. I don't believe
it. If this was 1975 then maybe.

I purposely posted a more convoluted explanation knowing about a million
people would come running out with qsort.

Yeah, I shouldn't have post it. I shut up.
 
R

Richard

John Bode said:
[snip]
the "got to get my name up" culture of this group

Says the man with 120 posts for the month of January *alone*.

You seem to miss the point.

The point is that it serves no purpose to post the SAME "off topic"
rebuke or the SAME answer as 20 people before hand unless you are giving
it a new angle. This groups was notorious for it. It has improved a
little.

A "thread" contribution when *discussing* something is also a different
matter.

I can explain further if that is not clear enough.
 
J

John Bode

John Bode said:
the "got to get my name up" culture of this group
Says the man with 120 posts for the month of January *alone*.

You seem to miss the point.

The point is that it serves no purpose to post the SAME "off topic"
rebuke or the SAME answer as 20 people before hand unless you are giving
it a new angle.

As opposed to you and Kenny and Twink posting the *same* personal
attacks on Heathfield ad nauseum? What "new angle" are you bringing
to those?
 
R

Richard

John Bode said:
John Bode said:

the "got to get my name up" culture of this group
Says the man with 120 posts for the month of January *alone*.

You seem to miss the point.

The point is that it serves no purpose to post the SAME "off topic"
rebuke or the SAME answer as 20 people before hand unless you are giving
it a new angle.

As opposed to you and Kenny and Twink posting the *same* personal
attacks on Heathfield ad nauseum? What "new angle" are you bringing
to those?

Yes. I thought that was why you popped in. I post "anti-heathfield"
replies occasionally because I think he's a pompous dickhead who is not
happy unless he is showing off and putting other people down. I hope
that clarifies things.
 
R

Richard

Richard said:
John Bode said:
[snip]

the "got to get my name up" culture of this group

Says the man with 120 posts for the month of January *alone*.

You seem to miss the point.

The point is that it serves no purpose to post the SAME "off topic"
rebuke or the SAME answer as 20 people before hand unless you are giving
it a new angle.

As opposed to you and Kenny and Twink posting the *same* personal
attacks on Heathfield ad nauseum? What "new angle" are you bringing
to those?

Yes. I thought that was why you popped in. I post "anti-heathfield"
replies occasionally because I think he's a pompous dickhead who is not
happy unless he is showing off and putting other people down. I hope
that clarifies things.

I neglected to mention that most of the time anything I have to say on
the issue tends to part of an ongoing discussion not a reply to an OP
asking for help. How you see the two connected I can only guess at.

If you would like to comment on the slightly more complex example I gave
of pointer to function then please feel free. If you feel you wish to
continue the discussion *you* initiated on the persecution, as you
perceive it, of Richard Heathfield then also please do - as part if an
ongoing thread it should not disrupt too many people who can mark the
thread as dead.
 
J

John Bode

If you feel you wish to
continue the discussion *you* initiated on the persecution, as you
perceive it, of Richard Heathfield then also please do - as part if an
ongoing thread it should not disrupt too many people who can mark the
thread as dead.

"Persecution" wasn't the word I was thinking of; more like
"pathological obsession."
 
A

Antoninus Twink

"Persecution" wasn't the word I was thinking of; more like
"pathological obsession."

Only in the upside-down world of the clc regulars could Heathfield be
seen as the victim! Do you really find it hard to see why people get
annoyed at Heathfield's pathological obsession with trying to put Jacob
down? Probably it's just penis-envy - Heathfield knows that for all his
posturing he would NEVER be able to write a C compiler.
 
R

Richard

John Bode said:
"Persecution" wasn't the word I was thinking of; more like
"pathological obsession."

Which is clearly nonsense. My point is simple : he's a strutting
egomaniac with a tendency to belittle people. Nothing "pathologically
obsessed" about reaching that conclusion.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,163
Latest member
Sasha15427
Top