Prateek Joshi
Prateek Joshi

Reputation: 4067

Return 2D array using static keyword in C

I was trying to return 2D integer array from a function in C. I was able to return it using dynamic memory allocation using malloc() but I am unable but curious to understand how can we use static keyword to do it.

Below is the code snippet which successfully returns 2D array using static keyword,

int (*(get_2d_arr_using_static)())[10]    // Can someone explain me this statement in detail ?
{
    static int arr[10][10] = { { 1,2,3}, {4,5,6}, {7,8,9}};
    return arr;
}

int main()
{
  int (*arr)[10] =  get_2d_arr_using_static();  // Need some insights on this statement too 
  printf("Result ( x: 3, y =3 ): \n");
  for (int i = 0; i < 3; i++)
  {
    for (int j = 0; j < 3; j++)
    {
      printf(" %d", arr[i][j]);
    }
    printf("\n");
  }
}

I need some explanation on the commented statements.

Upvotes: 0

Views: 131

Answers (1)

eerorika
eerorika

Reputation: 238461

I was trying to return 2D integer array from a function in C.

There's the problem. A function cannot return an array in C.

You can return pointers though, and pointers may point to an element of an array.

That array may be allocated dynamically or statically. Returning a pointer to an automatic array declared within the function would be pointless because the lifetime of that array ends when it goes out of scope, so you would be returning a dangling pointer.

int (*(get_2d_arr_using_static)())[10]    // Can someone explain me this statement in detail ?

This declares a function that returns a pointer to an array of 10 integers.

It should be noted that int[10][10] is an array of 10 arrays of 10 integers. As such, element of that array is an array of 10 integers, and the function returns a pointer to such element.

int (*arr)[10] =  get_2d_arr_using_static();  // Need some insights on this statement too 

This calls that function and initialises a pointer to an array of 10 integers.


It is possible to return an array by copy as well, but indirectly. It can be achieved by wrapping the array in a struct:

struct wrapper {
    int arr[10][10];
};


struct wrapper foo(void) {
     struct wrapper w;
     // fill the array or something
     return w;
}

Since you tagged C++, I'll mention that C++ standard library has a template for such wrapper class: std::array.

Upvotes: 1

Related Questions