I have written the following code to perform a simple matrices multiplication.
#include <stdio.h>
void op2(float *a_vec, int m, int n, int p, float *b_vec, float *c_vec){
float (*a)[n] = (float(*)[n]) a_vec;
float (*b)[p] = (float(*)[p]) b_vec;
float (*c)[p] = (float(*)[p]) c_vec;
int i, j, k;
for (i = 0; i<m; i++){
for(j=0; j<p; j++){
for(k=0; k<n; k++){
c[i][j] += a[i][k] * b[k][j];
}
printf("%.1f ", c[i][j]);
}
printf("\n");
}
}
int main(void){
float *aVec;
float *bVec;
float *cVec;
int m = 2;
int n = 3;
int p = 2;
float a[6] = {
1,3,1,
2,2,2
};
aVec = &a[0];
float b[6] = {
1,3,
1,2,
2,2
};
bVec = &b[0];
float c[4];
cVec = &c[0];
op2(aVec, m, n, p, bVec, cVec);
}
The resulting vector (printed to output) should be 6.0 11.0 8.0 14.0
Which it is... Most of the time.
However, sometimes it isn't. Sometimes the first value of the array will be incorrect. Most commonly it will be 5.7 or 5.8 5.8 11.0 8.0 14.0
My question is, what am I doing here that is causing this inconsistency? I'm quite new to C and my best guess is that perhaps I'm missing something with relation to the array indices, perhaps I'm running past the end of the array? But I don't see how it would happen inconsistently given that it has the same input, so maybe I'm missing something with pointers?
Have tried: Declaring array variables outside loops, changing values in input arrays.
cmatrix is uninitialized.aVecetc. variables? They are simply not needed. And inside theop2function, you cast them to the totally wrong type as well. If you want "2D" arrays (arrays of arrays) then use arrays of arrays. Don't mess around with different pointer types.ais 2×3.bis 3×2.cis 2×2.mis 2,nis 3, andpis 2. In the loops in the function,ais accessed by[i][k], andiandkare bound bymandnrespectively, which are 2 and 3, matching thatais 2×3. Forb[k][j],kandjare bound bynandp, which are 3 and 2, matching thatbis 3×2. Forc[i][j],iandjare bound bymandp, which are 2 and 2, matching thatcis 2×2.op2function, you cast them to the totally wrong type as well.”:float (*)[n],float (*)[p], and(float *)[p]withn=3 andp=2 are correct types for pointers to the first subarraysa(dimensions 2×3),b(3×2), andc(2×2), respectively. Why do you think they are wrong?