aslbj15
aslbj15

Reputation: 23

C: Matrix multiplication using double pointers

I've been given a code that reads in the matrix from two text files. (Assuming that is correct) I need to come up with a function that multiples two matrices together.

This is the given function prototype:

int** matMult(int **a, int num_rows_a, int num_cols_a, int** b, int num_rows_b, int num_cols_b);

And here is my code for the function:

int** matMult(int **a, int num_rows_a, int num_cols_a, int** b, int num_rows_b, int num_cols_b){

    int **c;

    c = (int**)malloc(sizeof(int*)*num_rows_a);
//    c = calloc(num_rows_a, num_cols_b);


    for (int i = 0; i < num_rows_a; i++) {
        for (int j = 0; j < num_cols_b; j++) {
            int sum = 0;
            for (int k = 0; k < num_cols_a; k++) {

                c[i][j] = a[i][k] * b[k][j] + sum;
                sum = c[i][j]; //so that previous answer gets stored 
            }
        }

    }
    return c;
}

I have to call malloc to allocate space for the resulting matrix, c

Also the issue I'm getting from Xcode is : EXC_BAD_ACCESS

Upvotes: 0

Views: 4652

Answers (2)

Stinson
Stinson

Reputation: 17

You need to allocate memory for columns too. :

int **c;

c = (int**)malloc(sizeof(int*)*num_rows_a);

for(i=0;i<num_rows_a;i++)
    c[i]=malloc(sizeof(int)*num_cols_b);    

Upvotes: 1

R Sahu
R Sahu

Reputation: 206747

The answer by @Stinson addresses the memory problem already. I'm going to suggest a little refinement of the inner block of code. There is no need to have temporary sum in the code.

for (int i = 0; i < num_rows_a; i++) {
  c[i] = malloc(sizeof(int)*num_cols_b);
  for (int j = 0; j < num_cols_b; j++) {

     // Initialize the element to zero.
     c[i][j] = 0;
     for (int k = 0; k < num_cols_a; k++) {
        // Accumulate the result
        c[i][j] += a[i][k] * b[k][j];
     }
  }
}

Upvotes: 0

Related Questions