Search code examples
cpointers2d

Returning 2d array using pointer to an array in c


#include <stdio.h>

int (*createArray())[3] {
    static int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};
    return arr;  
}

int main() {
    int (*ptr)[3] = createArray();

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

In this code while returning 2d array why we write like this 'int (*createArray())[3]'.while writing function, we use

return_type function_name ( parameter_list)
{
   // function body
}

But in this code why we need to write function name between the return type


Solution

  • But in this code why we need to write function name between the return type

    In C, declarations are written to give a “picture” of how a variable will be used. Kernighan and Ritchie wrote, in The C Programming Language, 1978, page 90:

    The declaration of the pointer px is new.

    int *px;

    is intended as a mnemonic; it says the combination *px is an int, that is, if px occurs in the context *px, it is equivalent to a variable of the type int. In effect, the syntax of the declaration for a variable mimics the syntax of expressions in which the variable might appear. This reasoning is useful in all cases involving complicated declarations. For example,

    double atof(), *dp;

    says that in an expression atof() and *dp have values of type double.

    So int (*createArray())[3] says:

    • The type of (*createArray())[3] is int.
    • Therefore (*createArray()) is an array of 3 int.
    • Therefore createArray() is a pointer to an array of 3 int.
    • Therefore createArray is a function returning a pointer to an array of 3 int.

    So the need to embed the name inside the declarators arises out of the decision to make a declaration be a picture of how the name will be used.