Search code examples
cpointersfunction-pointers

Understanding a pointer function that returns a pointer to an array


So, I am just trying to wrap my head around "pointer function that returns a pointer to an array"... but to start off slowly, I had to understand this:

void Print(const char c){
    printf("\nPrint: %c\n", c);
}

int main () {
    void (*FunctionPointer)(const char);
    FunctionPointer = &Print;
    FunctionPointer('a');
}

Which I do - pretty easy to guess what is going on... FunctionPointer just points to the location where the Print function "resides". Instead of jumping to a specific memory address (stored on a register) of a specific function, I can now be more flexible and point to any function that I want to access.

But I am stuck with the following...

int main () {
    int (*FunctionPointer())[];
}

Now it seems that the function that is pointed by FunctionPointer, can in fact return a pointer to an array of type int. The compiler accepts the second line - so far so good - and I also understand the concept... but I am getting stuck regarding the implementation.

FunctionPointer needs - once again, to point to a function. That function can indeed return a pointer that points to an array of type int... soooooo:

int *Array(){
    int ar[2] = {5,6};
    return ar;
}

int main () {
    int (*FunctionPointer())[];
    FunctionPointer = &Array;
}

However, the last piece of code is just not accepted by the compiler.... So, what gives?


Solution

  • With

    int (*FunctionPointer())[];
    

    you've declared FunctionPointer as a function returning a pointer to an array of int -- not a function pointer. You want

    int *(*FunctionPointer)();
    

    If you use [] here, you'll get an error, as functions can't return arrays -- arrays are not first class types -- and unlike with function parameters, arrays will not be silently converted to pointers when used as the return value of a function type. With that, you'll still get the warning

    t.c:3:12: warning: function returns address of local variable [-Wreturn-local-addr]
         return ar;
                ^~
    

    which is pretty self-explanatory