views:

71

answers:

3

hi everybody, i can't understand following defining pointer variable. can you help me?

double(*)(double *) foo;

note : sory, i edit name of variable func to foo.

A: 

it's a pointer to a function returning double having a parameter of type pointer to double, if you correct the variable declaration since as it stands its just incorrect correct syntax would be double (*foo) (double*)
uses are polymorphism by being able to replace a function:

struct memory_manager{
    void*(*getmem)(size_t);
    void(*freemem)(void*);
}mem_man; 
void* always_fail(size_t){return 0;}
void* myalloc(size_t s){
    void* p=mem_man.get_mem(s);
    if(p) return p;
    mem_man.getmem=always_fail;
    return 0;
}
void myfree(void* p){
    if(p) freemem(p);
}

it's not really the c++-way i geuss, since for most purposes inheritance and virtual functions offer a better solution, but if you're restricted to c, then you can use this technique to simulate virtual functions.

flownt
i must say i find it pretty annoying that i get a downvote here, because i missed an error in the question, i did my best to answer as fast as possible, it was all with the best intentions.
flownt
@flownt: Edit your answer, and I'll remove the downvote!
Oli Charlesworth
@flownt: I was not the downvoter but best intentions don't get good answers, and an answer is rated as an answer, and not as an intention
Armen Tsirunyan
@flownt: Ok, downvote removed. But that code example is very terse!
Oli Charlesworth
+7  A: 

This is not valid C. Perhaps you mean this:

double(*func)(double *);

which declares func as a pointer to a function that takes a pointer-to-double, and returns a double.

You can use http://cdecl.org for this sort of thing.

Oli Charlesworth
func is not a function, just variable name.
cmuse
@cmuse: I didn't say it was a function!
Oli Charlesworth
sory, i missed out.
cmuse
thanks to your explain, it is useful for me.
cmuse
A: 

Try this (tested):

// functions that take double * and return double
double dfunc(double *d) { return (*d) * 2.0; }

double tfunc(double *d) { return (*d) * 3.0; }

int main()
{
    double val = 3.0;

    double       // 3. the function returns double
    (*pFunc)     // 1. it's a pointer to a function 
    (double *);  // 2. the function takes double *

    pFunc = dfunc;

    printf("%f\n", pFunc(&val)); // calls dfunc()

    pFunc = tfunc;

    printf("%f\n", pFunc(&val)); // calls tfunc()
}

Output:

6.000000
9.000000

egrunin
you forgot an assignment: func=dfunc;
flownt
@flownt: fixed, thanks.
egrunin