0

I'm defining a matrix, A, and I just want to print it out:

#include <stdio.h>

#define N 4

double A[N][N]= {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12},
        {13, 14, 15, 16}
};

void print_matrix(double **A) {
    int i, j;
    for(i = 0; i < N; i++) {
        for(j = 0; j < N; j++) {
            printf("%f ", A[i][j]);
        }
        printf("\n");
    }
}

int main() {
    print_matrix(A);
}

But on compile I get the error: expected 'double **' but argument is of type 'double (*)[4]'

I tried in the main function to pass the matrix like print_matrix(&A); but then the error was expected 'double **' but argument is of type 'double (*)[4][4]'

Nermin
  • 749
  • 7
  • 17
  • @Lundin Yes. Thank you for catching that. – Fiddling Bits Apr 30 '20 at 13:08
  • Does this answer your question? [How to pass a multidimensional array to a function in C and C++](https://stackoverflow.com/questions/2828648/how-to-pass-a-multidimensional-array-to-a-function-in-c-and-c) – einpoklum Aug 24 '21 at 21:52

2 Answers2

3

Pointer-to-pointer has nothing to do with multi-dimensional arrays. Simply declare the function as void print_matrix(double A[N][N]).

Thanks to "array decay", this passes the array by reference, since double A[N][N] when part of a parameter list, gets implicitly "adjusted" into a pointer to the first element, double (*A)[N].

Lundin
  • 195,001
  • 40
  • 254
  • 396
0

There are multiple ways of defining a multidimensional array in C - and they have different exact semantics and behaviors w.r.t. passing to functions.

The approach you chose actually defines a single contiguous sequence of elements, which the double-bracketed access simply calculates an index into; it doesn't actually go through an array of pointers.

But you could also create an array of pointers and a large purely-unidimensional array for the entire data. See C FAQ 6.16.

einpoklum
  • 118,144
  • 57
  • 340
  • 684