Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does function "int (*function())[10];" mean?

Tags:

c++

c

I read a piece of code and find there is a function like that.

int (*function())[10]{
 ...
}

I am confused. What does this function mean and what will it return?

like image 400
Muris Avatar asked Jun 09 '13 18:06

Muris


2 Answers

It is the definition of a function that returns a pointer to an array of 10 integers.

Remember that the return value is a pointer, not an actual array. Arrays cannot be returned from functions. Per paragraph 8.3.5/8 of the Standard:

Functions shall not have a return type of type array or function, although they may have a return type of type pointer or reference to such things

Here's a simple example of how you would use it:

int arr[10];     // an array of 10 int
int (*ptr)[10]; // pointer to an array of 10 int

int (*function())[10] // function returning a pointer to an array of 10 int
{
    return ptr;
}

int main()
{
    int (*p)[10] = function(); // assign to the pointer
}

You can use this wherever you would normally use a pointer. But note that there are better alternatives than pointers altogether, like std::shared_ptr<std::array<T, N>> or std::shared_ptr<std::vector<T>>.

like image 146
David G Avatar answered Oct 07 '22 15:10

David G


The way to read it is to find the leftmost identifier and work your way out, remembering that () and [] bind before *, so *a[] is an array of pointers, (*a)[] is a pointer to an array, *f() is a function returning a pointer, and (*f)() is a pointer to a function. Thus,

      function          - function
      function()        - is a function
     *function()        - returning a pointer
    (*function())[10]   - to a 10-element array
int (*function())[10]   - of int
like image 39
John Bode Avatar answered Oct 07 '22 15:10

John Bode