3

I have this code for matrix multiplication, but its given me a compilation error. I need t have a function that receives as arguments the pointers for the 3 matrices and their dimension N.

#include <stdio.h>
#define N 100

void matrixmul(int **matA, int **matB, int **matC, int n){

    int i,j,k;

    for(i=0;i<n;i++){   
    for(j=0;j<n;j++){
        matC[i][j] = 0;
        for(k=0;k<n;k++){
        matC[i][j] += matA[i][k] * matB[k][j];
        }
    }
    }

}

int main(){

    int matA[N][N]={1};
    int matB[N][N]={3};
    int matC[N][N];

    int i,j,k;

    matrixmul(&matA, &matB, &matC, N);

    for(i=0;i<N;i++){   
    for(j=0;j<N;j++){
        printf("%d ", matC[i][j]);
    }
    printf("\n");
    }

    return 0;

}

The error is:

teste.c: In function ‘main’:
teste.c:28:5: warning: passing argument 1 of ‘matrixmul’ from incompatible pointer type [enabled by default]
teste.c:5:6: note: expected ‘int **’ but argument is of type ‘int (*)[100][100]’
teste.c:28:5: warning: passing argument 2 of ‘matrixmul’ from incompatible pointer type [enabled by default]
teste.c:5:6: note: expected ‘int **’ but argument is of type ‘int (*)[100][100]’
teste.c:28:5: warning: passing argument 3 of ‘matrixmul’ from incompatible pointer type [enabled by default]
teste.c:5:6: note: expected ‘int **’ but argument is of type ‘int (*)[100][100]’

3 Answers3

2

Pointers are not arrays.
All of the &matA, &matB and &matC are of type int (*)[100][100] (pointer to an array of 100 arrays of 100 integers) but your function matrixmul is expecting parameters of type int ** (except for N: int type).
Change your function definition to

void matrixmul(int (*matA)[N], int (*matB)[N], int (*matC)[N], int n){ ... }  

and call it from main as

 matrixmul(matA, matB, matC, N);
haccks
  • 104,019
  • 25
  • 176
  • 264
2

You can try these changes.

void matrixmul(int matA[][N], int matB[][N], int matC[][N], int n)

and can call this function like this

matrixmul(matA, matB, matC, N);
Vishal R
  • 1,026
  • 1
  • 7
  • 21
1

The error is caused by the fact that a pointer to a pointer is different by an array. An array is a fixed-length collection of objects, which are stored sequentially in memory. An pointer to a pointer even if it can be used as as an array the compiler doesn't guarantee that the memory of the 2d matrix is continuous. One way to decalare your fonction is:

void matrixmul(int matA[][N], int matB[][N], int matC[][N], int n)

If you want to pass de matrix as a pointer to a pointer you have to alloc the memory like this:

int **array = new int *[N];

for(int i = 0; i<N; i++)

    array[i] = new int[N];`
Ilie NEACSU
  • 530
  • 3
  • 12