'Matrix Multiplication using 1D arrays in C, formula and order?

I have this code to multiply two matrices stored in 1D arrays.

#include <stdlib.h>
#include <assert.h>
#include <stdint.h>
#include <stdio.h>

void matrix_multiplier(int n, int m, int k,
            double* C, double* arr_1, double* arr_2) {
  
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < k; j++) {
            int sum = 0;
            for (int p = 0; p < m; p++)
                sum = sum + A[p + i * k ] * B[j + p * n];
            C[j + i * n] = sum;
        }
    }
}



int main(){

  int n = 3;
  int m = 3;
  int k = 2;
    
  double arr_1[10] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0};

  double arr_2[10] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0};

  double *C = calloc(n*k, sizeof(double));


  matrix_multiplier(n, m, k, C, arr_1, arr_2);


  printf("\n");
  printf("input matrices\n");

   for (int j = 0; j < n; ++j) {
        for (int i = 0; i < m; ++i) {
             printf("%f ", arr_1[j * m+ i]);
        }
        printf("\n");
    }


  printf("\n");


  for (int j = 0; j < n; ++j) {
        for (int i = 0; i < m; ++i) {
             printf("%f ", arr_2[j * m+ i]);
        }
        printf("\n");
    }


   printf("output matrix\n");

   for (int j = 0; j < n; ++j) {
        for (int i = 0; i < m; ++i) {
             printf("%f ", C[j * m+ i]);
        }
        printf("\n");
    }


     free(C);

    return 0;
}

However I'm not sure sum = sum + A[p + i * k ] * B[j + p * n]; line is entirely correct. I tried following some pseudocode and it led me only to this. Furthermore, I'm not quite sure if this code is storing the data in row-major or column-major order, cause i do actually need it to be in row-major.



Solution 1:[1]

Using integer for accumulation of doubles is a bad idea: Replace:

int sum = 0;

with

double sum = 0;

Another issue is indexing the C array. It should be:

C[j + i * k] = ...

For every increment of i by 1, the j is incremented k times.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tstanisl