Search code examples
cmatrixmultidimensional-arrayparameter-passing

How to pass static matrix in a function with poiners in C?


I need to optimize by memory program, so I decided to use pointers with static matrix, but i I don't know much about pointers in C, and the program doesn't work(in VS program throws exceptions)

#include <stdio.h>

int Sumofsum(int **matrix, int size) {
    int sum = 0;
    for (int i = 0; i < size; ++i) {
        for (int j = 0; j < size; ++j) {
            sum += matrix[i][j];
        }
    }
    return sum;
}

void SumofSumOut(int sum) {
    printf("Sum of sums of elements in those rows: %d\n", sum);
}

int main() {
    int matrix[5][5] =
            {
                    {21,8, 3, 4, 5},
                    {1, 3, 5, 7, 9},
                    {2, 4, 6, 8, 9},
                    {1, 3, 4, 5, 7},
                    {3, 3, 3, 3,11}
            };
    int sum, size = 5;
    sum = Sumofsum(matrix, size);
    SumofSumOut(sum);
    return 0;
}

i tried to use (*matrix)[5], but it's not what I need


Solution

  • int **matrix indicates a pointer to pointer. It's what int *matrix[] would degrade into.

    You don't have an array of pointers.


    Treat the array as 1d:

    int sum_of_sum( int *matrix, int size ) {
        int sum = 0;
        for ( int i = 0; i < size; ++i ) {
            for ( int j = 0; j < size; ++j ) {
                sum += matrix[ i * size + j ];
            }
        }
        return sum;
    }
    
    sum_of_sum( &matrix[0][0], size )
    

    Pass a pointer to the first row.

    int sum_of_sum( int size, int (*matrix)[ size ] ) {
        int sum = 0;
        for ( int i = 0; i < size; ++i ) {
            for ( int j = 0; j < size; ++j ) {
                sum += matrix[i][j];
            }
        }
        return sum;
    }
    
    sum_of_sum( size, matrix );
    

    Pass a pointer to the array.

    int sum_of_sum( int size, int (*matrix)[ size ][ size ] ) {
        int sum = 0;
        for ( int i = 0; i < size; ++i ) {
            for ( int j = 0; j < size; ++j ) {
                sum += matrix[i][j];
            }
        }
        return sum;
    }
    
    
    sum_of_sum( size, &matrix );