【发布时间】:2018-12-11 17:14:39
【问题描述】:
这是我正在开发的程序。任务是乘以 2 个矩阵。矩阵 A 中的列数与矩阵 B 中的行数相同。我让用户可以选择插入两个矩阵包含的内容。 这是我的代码:
#include <stdio.h>
void multiplyMat(int n,int p,int c,int m,int d,int q,int k,int **multiply,
int **first,int **second);
int main()
{
int m, n, p, q, c, d, k;
int first[10][10], second[10][10], multiply[10][10];
printf("Enter number of rows and columns of first matrix\n");
scanf("%d%d", &m, &n);
printf("Enter elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter number of rows and columns of second matrix\n");
scanf("%d%d", &p, &q);
printf("Enter elements of second matrix\n");
for (c = 0; c < p; c++)
for (d = 0; d < q; d++)
scanf("%d", &second[c][d]);
multiplyMat(n,p,c,m,d,q,k,multiply,first,second);
printf("Product of the matrices:\n");
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++)
printf("%d\t", multiply[c][d]);
printf("\n");
}
return 0;
}
void multiplyMat(int n,int p,int c,int m,int d,int q,int k,int **multiply,
int **first,int **second){
int sum=0;
if (n == p){
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++) {
for (k = 0; k < p; k++) {
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}
}
else
printf("The matrices can't be multiplied with each other.\n");
}
我得到“分段错误”。 它发生在代码进入“sum = sum + first[c][k]*second[k][d]”时 我做了什么导致它? 可能是因为我使用了错误的指针定义。
【问题讨论】:
-
int **multiply与您的first[10][10]不同。当您打开警告时,您的编译器会告诉您什么? -
@PaulOgilvie:他可能需要更多的解释。
-
搜索
[c] segmentation fault passing 2D array会产生 plethora 这个问题的重复项。你这样做了吗? -
指针first/second/multiply衰减到的类型不是
int**,而是int(*)[10],即。 e.指向长度为 10 的数组的指针,所以完全不同... -
要了解实际数组和指向
int **first等指针的指针之间的区别,这个问题和答案高度相关:Correctly allocating multi-dimensional arrays
标签: c