0

My problem is the following: I want to give the function my matrix (2D array) but in fact I have tried a lot to achieve this but I missed the point with every try. I just found solutions were the function head should be changed but that's exactly what I want to avoid.

So my function is this:

void print_matrix(int **const mat, int n) { 
    
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++){
            printf("%d  ",mat[j][i]);
        }
        printf("\n");
    }

 }

And my call looks like this: (I want to change just the call of the function not the declaration of the array_a)

int array_a[4][4];
print_matrix(array_a, 4);

or

print_matrix(&array_a, 4);

or

print_matrix(**array_a, 4);

and so on..

Pukka
  • 31
  • 4
  • You must understand that `int**` has nothing to do with an array. It is a *pointer-to-pointer-to* `int` -- that is a single pointer to a block of pointers. While `int array_a[4][4];` is an *array-of-arrays* `int[4]` which by virtue of array-pointer conversion is typed `int (*)[4]` *pointer-to-array-of* `int[4]`. A *pointer-to-pointer* and *pointer-to-array* are two entirely separate types. – David C. Rankin Dec 02 '20 at 23:19
  • 1
    If you are still unclear that means `void print_matrix(int (*mat)[4], int n) {` – David C. Rankin Dec 03 '20 at 00:03
  • ah okay thank you! But is there also another option to make this.. with changing the declaration of ´array_a´ and not the head of the function? :) @DavidC.Rankin – Pukka Dec 03 '20 at 00:08
  • Yes, but then you are allocating for what should be a simple 2D array with automatic storage duration. Obviously, if you don't know how many rows or columns you will have, then allocating pointers for rows and `int` for columns makes sense. If it will always be an array of `int[4]` and you just don't know the number of rows, then allocate blocks of 4-`int`, e.g. `int (*mat)[4] = malloc (nrows * sizeof *mat);` If it is fixed-size, (and below what will cause StackOverflow (roughly 200K `int` with a 1M stack leaving adequate storage for other variables) just use a fixed 2D array. All have uses. – David C. Rankin Dec 03 '20 at 00:15

0 Answers0