开发者

definition pointer variable

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

double(*)(double *) foo;

note : sory, i edi开发者_如何学Pythont name of variable func to foo.


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜