user3425117
user3425117

Reputation: 3

passing a 2d subarray in c

I have a 2D array A and a recursive function

`// A is a 2D array,n11: no. of rows in A, n12: no. of columns in A
void rotate(int** A, int n11, int n12)
{
    //do something
    //pass sub-array starting at A[1][1] having n11-2 rows and n12-2 columns
    rotate(???,n11-2,n12-2);
}`

the malloc for A has been done in the calling function. The prototype of the function can't be modified.

Upvotes: 0

Views: 672

Answers (1)

AnT stands with Russia
AnT stands with Russia

Reputation: 320491

According to your function parameter declaration (int** A), the 2D array is implemented as a "jagged array" (i.e. a top-level 1D array of pointers to 1D subarrays).

It is not possible to create a jagged 2D subarray you described without introducing and initializing some extra data. In order to produce such 2D subarray, you will have to create a new top-level 1D array of pointers, initialize it accordingly and pass it further down the line

void rotate(int **A, int n11, int n12)
{
  //pass sub-array starting at A[1][1] having n11-2 rows and n12-2 columns

  int *sub_A[n11 - 2];
  for (int i = 0; i < n11 - 2; ++i)
    sub_A[i] = &A[i + 1][1];

  rotate(sub_A, n11 - 2, n12 - 2);
}

As an additional note, you have to keep in mind that all modifications you do to A[i][j] inside rotate at any level of recursion will affect the primary 2D array in main. But modifications you do to A[i] pointers at lower levels of recursion will not affect the primary array (since we create a new independent copy of it at each level of recursion). But I assume that this is not a problem, since (judging by the function name) all modifications are probably done through A[i][j] interface. BTW, for this reason, it would actually make more sense to declare the function as

void rotate(int *const *A, int n11, int n12)

That const will prevent modifications of the top-level pointer array, i.e. it will let you modify the 2D array's contents, but not the array's structure.

Anyway, here's a live example of this technique in action: https://ideone.com/Sm40iD (I simply print the 2D array there).

Upvotes: 2

Related Questions