-2
int (*get_2d_array(void))[3]    //This Function
{
    static int arr[2][3] = { 10, 20, 30, 40, 50, 60 };
    return arr;
}


int main()
{

int i, j, row = 2, col = 3;
int (*ptr)[col];

ptr = get_2d_array();

for( i = 0; i < row; i++ )
{
    for( j = 0; j < col; j++ )
    {
        printf("%d ",ptr[i][j]);
    }
    printf("\n");
} 
    return 0;
}

This function is declared like an array, can somebody help me in interpreting this function declaration?

The function output is that it prints the array returned by the function called.

Raj Kumar Mishra
  • 516
  • 4
  • 16

2 Answers2

2

Function returning a pointer to array of size 3 of int.

You may use solutions such as https://cdecl.org to translate in future.

However, I have found somewhere a method that allows to "translate" without the use of external tools. You begin reading with the identifier, then move right, when you encounter a closing brace you "bounce back".

With your function it works as follows:

  • you begin with the identifier: get_2d_array, so we have "get_2d_array is a..."

  • we move right, when we have (void), so it looks like a function declaration: "get_2d_array is a function that takes no arguments and returns..."

  • we move further right, encounter unbalanced closing brace, so we bounce back and discover an asterisk, which signifies a pointer; we have therefore "get_2d_array is a function that takes no arguments and returns a pointer to ..."

  • OK, going right again we encounter [3], so we plug it into our sentence: "get_2d_array is a function that takes no arguments and returns a pointer to an array of size 3 of..."

  • the last thing we didn't interpret is an 'int' in the beginning, so we have finally: "get_2d_array is a function that takes no arguments and returns a pointer to an array of size 3 of int"

lukeg
  • 4,189
  • 3
  • 19
  • 40
0

int (*get_2d_array(void))[3] takes no arguments (void) and returns a pointer to an array of ints with with 3 elements in the second dimension ("columns").

atru
  • 4,699
  • 2
  • 18
  • 19
  • If that the case, then is this correct? int *get_2d_array(void)[3] Because if it is an int pointer returning array with 3 column then the bracket should be omitted. Otherwise its return type is integer – Raj Kumar Mishra Oct 01 '17 at 18:30
  • May actually not be because of precedence. Let me check. – atru Oct 01 '17 at 18:31
  • Indeed, check [this one](https://stackoverflow.com/questions/859634/c-pointer-to-array-array-of-pointers-disambiguation). Without the brackets the return type will be array of int pointers. – atru Oct 01 '17 at 18:34
  • Sorry for the confusion, I haven't understood your comment at first. This is correct if you want the pointer to the array and not an array of pointers which arr certainly is not at this point. The compiler throws a warning on the second version. It's not returning an integer, but just as said in the answer. – atru Oct 01 '17 at 18:50