问题
void multiply(int a[], int row1, int col1, int b[], int row2, int col2) {
int d[size];
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col2; j++) {
int sum = 0.0;
for (int k = 0; k < col2; k++)
sum = sum + a[i * col1 + k] * b[k * col2 + j];
d[i * col2 + j] = sum;
}
}
for (int i = 0; i < size; i++) {
if (i % col2 == 0) {
printf("\n");
}
printf("%d ", d[i]);
}
}
I have this as a function to multiple two one-dimensional arrays that are supposed to be matrices. I'm using an online compiler and it just gives me nothing when I run the code.
EDIT:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int size = 8;
void multiply(int a[], int row1, int col1, int b[], int row2, int col2) {
int d[size];
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col2; j++) {
int sum = 0.0;
for (int k = 0; k < col2; k++) {
sum = sum + a[i * col1 + k] * b[k * col2 + j];
}
d[i * col2 + j] = sum;
}
}
for (int i = 0; i < size; i++) {
if (i % col2 == 0) {
printf("\n");
}
printf("%d ", d[i]);
}
}
int main() {
int a[size] = {
1, 2, 3, 4, // 0 1 2 3
5, 6, 7, 8 // 4 5 6 7
};
int c[size] = {
1, 4, // 0 1
2, 3, // 2 3
3, 2, // 4 5
4, 1 // 6 7
};
printf("Multipying Matrices\n");
multiply(a, 2, 4, c, 4, 2);
}
This is the entire code that I run to test out the multiplication function from Costantino Grana but edited it because I haven't gone into memory allocation.
The result of this code is:
5 10
17 38
2 4
6 8
This is already wrong because the multiplication of the two matrices should result in a 2x2 matrix.
回答1:
Here is a fixed version with a Minimal, Complete, and Verifiable example, which you should have posted.
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
void multiply(int *a, int row1, int col1, int *b, int row2, int col2)
{
assert(col1 == row2);
int size = row1*col2;
#ifdef _MSC_VER
int *d = malloc(size * sizeof *d);
#else
int d[size];
#endif
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col2; j++) {
int sum = 0;
for (int k = 0; k < col1; k++)
sum = sum + a[i * col1 + k] * b[k * col2 + j];
d[i * col2 + j] = sum;
}
}
for (int i = 0; i < size; i++) {
if (i % col2 == 0) {
printf("\n");
}
printf("%d ", d[i]);
}
#ifdef _MSC_VER
free(d);
#endif
}
int main(void)
{
int a[] = {
1, 2, 3,
4, 5, 6,
};
int b[] = {
7, 10,
8, 11,
9, 12,
};
multiply(a, 2, 3, b, 3, 2);
}
Apart having a solution for avoiding VLAs, the mistake was in the inner loop which should run up to col1 or row2, not col2.
By the way: I'd avoid passing col1 and row2. These should be the same. I substituted a[]
and b[]
with *a
and *b
, which is closer to the real thing (my opinion). Moreover you should avoid mixing computation and printing. Have your function return a new matrix and another function to print matrices.
Finally, use a struct to keep the data pointer, rows and cols together.
来源:https://stackoverflow.com/questions/47023651/multiplying-matrices-in-one-dimensional-arrays