Short answer : you can't do that with simple arrays in C. A function that receives an array as a parameter has no way of knowing the dimensions.
The first solution I can think of to make this possible is to use a structure that will hold a pointer to the first value of the matrix and its dimensions.
#include <stdio.h>
#include <math.h>
typedef struct
{
unsigned int size_x;
unsigned int size_y;
double *data;
} mat2D_t;
double A_data[3][3] = {
{1.23,0,0},
{0,1,0},
{0,0,1}
};
double B_data[3][3] = {
{1,0,0},
{0,1,0},
{0,0,1}
};
double C_data[3][3];
mat2D_t A = {
.size_x = 3,
.size_y = 3,
.data = (double*)A_data,
};
mat2D_t B = {
.size_x = 3,
.size_y = 3,
.data = (double*)B_data,
};
mat2D_t C = {
.data = (double*)C_data,
};
int mat_mul(mat2D_t* a, mat2D_t* b, mat2D_t* res)
{
unsigned int dim_ax = a->size_x;
unsigned int dim_ay = a->size_y;
unsigned int dim_bx = b->size_x;
unsigned int dim_by = b->size_y;
if (dim_by != dim_ax)
return -1; // cannot multiply
res->size_y = dim_ay;
res->size_x = dim_bx;
for (int y = 0; y < dim_ay; y++)
{
for (int x = 0; x < dim_bx; x++)
{
int index = y*dim_bx + x;
res->data[index] = 0;
for (int i = 0; i < dim_ax; i++)
{
res->data[index] += a->data[y*dim_ax + i]
* b->data[i*dim_bx + x];
}
}
}
return 0;
}
int main(void){
if (mat_mul(&A, &B, &C) != 0)
{
printf("dimensions error\n");
}
else
{
for (int y = 0; y < C.size_y; y++)
{
for (int x = 0; x < C.size_x; x++)
{
printf("%5.2f ", C.data[y*C.size_x + x]);
}
putchar('\n');
}
}
return 0 ;
}
Note that you should also try to avoid global variables as much as possible.
You can also provide the dimensions of an array in the parameters of the function by putting the dimensions before the array :
void foo(int ax, int ay, double a[ay][ax])
But using this in a function that must return the result of the multiplication will be a bit difficult, and this may not be possible with th program you want to write.