Home > Software engineering >  Understanding a pointer function that returns a pointer to an array
Understanding a pointer function that returns a pointer to an array

Time:06-05

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?

CodePudding user response:

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

CodePudding user response:

You have declared the array of function pointers. Arrays can't be assignable. Functions can't return arrays. You might wish

int* (*FunctionPointer)();
FunctionPointer = &Array;

CodePudding user response:

Function pointers are much easier when you use typedefs. You can simply use the same notation as "normal" data pointers.

// func is a function type. It has one parater and returns pointer to int
typedef int *func(const char);

// funcptr is a pointer to func
func *funcptr;
  • Related