How define an array of function pointers in C

前端 未结 5 1546
野趣味
野趣味 2020-11-28 02:05

I\'ve a little question. I\'m trying to define an array of function pointers dynamically with calloc. But I don\'t know how to write the syntax. Thanks a lot.<

5条回答
  •  一整个雨季
    2020-11-28 02:39

    You'd declare an array of function pointers as

    T (*afp[N])(); 
    

    for some type T. Since you're dynamically allocating the array, you'd do something like

    T (**pfp)() = calloc(num_elements, sizeof *pfp);
    

    or

    T (**pfp)() = malloc(num_elements * sizeof *pfp);
    

    You'd then call each function as

    T x = (*pfp[i])();
    

    or

    T x = pfp[i](); // pfp[i] is implicitly dereferenced
    

    If you want to be unorthodox, you can declare a pointer to an array of pointers to functions, and then allocate that as follows:

    T (*(*pafp)[N])() = malloc(sizeof *pafp);
    

    although you would have to deference the array pointer when making the call:

    x = (*(*pafp)[i])();
    

提交回复
热议问题