Nermin
Nermin

Reputation: 935

How to pass matrix to function by reference in C?

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]'

Upvotes: 0

Views: 772

Answers (2)

einpoklum
einpoklum

Reputation: 132250

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.

Upvotes: 0

Lundin
Lundin

Reputation: 215115

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].

Upvotes: 3

Related Questions