I am trying to implement a function that multiplies two dynamic matrices (AxB) and returns a pointer to the dynamically allocated product (C). The arguments of the function are:
- pointer to matrix A
- a_rows, number of rows in A
- a_cols number of columns in A
- pointer to matrix B
- b_cols, number of columns in B
Since the product will have the same number of rows as A and the same number of columns as B, a_rows and b_cols are used to determine the size of the product to be allocated.
The function is as shown:
double** MatrixMultiply(
double** a,
const uint32_t a_rows,
const uint32_t a_cols,
double** b,
const uint32_t b_cols) {
double** c;
c = (double**) calloc(a_rows, sizeof(double**)); //product matrix C has
//matrix A rows and Matrix B cols
for(int32_t i = 0; i < a_rows; i++) {
c[i] = (double*) calloc(b_cols, sizeof(double*));
}
for(uint32_t i = 0; i < a_rows; i++) {
for(uint32_t j = 0; j < b_cols; j++) {
for(uint32_t k = 0; k < a_cols; k++) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
return c;
}
The problem is that whenever I run my program it gets crashed by the function because of what I assume is some sort of segmentation fault. However, whenever I run the debugger and step through each line, it never shows that any errors have occurred.
What is strange to me is that when I change "a_rows" and "b_cols" to a constant (e.g., 20) the function runs correctly. What could be causing this problem? And how can it be fixed? Any help would be greatly appreciated.