C 我的代码有分段错误
我对C很陌生,但我不知道为什么会出现这个错误。我知道分割错误是由于超出了我的范围,但我不知道我在哪里C 我的代码有分段错误,c,C,我对C很陌生,但我不知道为什么会出现这个错误。我知道分割错误是由于超出了我的范围,但我不知道我在哪里 #包括 #包括 int**totalMatrix(int numRows、int numCols){ 整数矩阵; 整数矩阵; int**sumMatrix; int row,col; printf(“输入矩阵A\n”); 第一矩阵=(int**)malloc(numRows*sizeof(int*); 对于(行=0;行
#包括
#包括
int**totalMatrix(int numRows、int numCols){
整数矩阵;
整数矩阵;
int**sumMatrix;
int row,col;
printf(“输入矩阵A\n”);
第一矩阵=(int**)malloc(numRows*sizeof(int*);
对于(行=0;行
提前感谢。对于
firstMatrix
和secondMatrix
您正确地malloc
外部维度,然后在一个循环中,malloc
所有内部维度
出于某种原因,对于sumMatrix
,您只需malloc
'd外部维度。它存储的所有指针都未初始化,但您正在取消引用它们
请注意,当我说“正确”时,我使用了松散的术语:这是大量不必要的动态分配!喜欢一个大的分配。可以在单个内存块上映射二维索引。这也可以避免这个错误
此外,函数始终返回
0
。这是一个空指针。因此,当您在main
中使用它并将其传递给delete\u matrix
时,这是没有意义的。我将完全取消返回,并将delete_matrix
调用移动到totalMatrix
(啊!函数命名不一致!)的底部,因为您实际上需要执行三次,每个矩阵一次。欢迎使用StackOverflow!你应该将相关代码粘贴到问题中。而且,现在听起来可能是浪费,但实际上这是开始学习如何使用调试器的最佳时机。不要标记不相关的语言。这是pastebin链接。我们知道。没关系。在sumMatrix中缺少一个malloc
,而在colsOh man中没有,我完全错过了。我刚把它修好;然而,它仍然存在。我甚至不知道你可以,我得调查一下,谢谢@Motosuwa:发现了另一个bug。是的,我正在修补它,试图弄清楚为什么在我发布之前它不工作。我甚至抓取了一些代码,这就是为什么名称不一致的原因。我现在就去修。谢谢它现在正常工作了,非常感谢你!。但我不太明白你什么时候想把它加到totalMatrix的底部。你的意思是将其传递到函数中吗?难道我不需要再添加一个参数,它会变得更混乱吗?@Motosuwa:不,只需从totalMatrix
中调用delete\u matrix
,每次需要删除一个矩阵就调用一次。如果您不这样做,您仍然需要在main
中向其当前位置添加两个额外的调用,以某种方式将矩阵的指针指向该位置,这肯定会很混乱!
#include <stdlib.h>
#include <stdio.h>
int** totalMatrix(int numRows, int numCols){
int** firstMatrix;
int** secondMatrix;
int** sumMatrix;
int row, col;
printf("Enter Matrix A\n");
firstMatrix = (int**)malloc(numRows * sizeof(int*));
for(row = 0; row < numRows; row++){
firstMatrix[row] = (int*)malloc(numCols * sizeof(int));
}
for(row = 0; row < numRows; row++){
for(col = 0; col < numCols; col++){
scanf("%d", &firstMatrix[row][col]);
}
}
printf("Enter Matrix B\n");
secondMatrix = (int**)malloc(numRows * sizeof(int*));
for(row = 0; row < numRows; row++){
secondMatrix[row] = (int*)malloc(numCols * sizeof(int));
}
for(row = 0; row < numRows; row++){
for(col = 0; col < numCols; col++){
scanf("%d", &secondMatrix[row][col]);
}
}
printf("A + B =\n");
sumMatrix = (int**)malloc(numRows * sizeof(int*));
for(row = 0; row < numRows; ++row){
for(col = 0; col < numCols; ++col){
sumMatrix[row][col] = firstMatrix[row][col] + secondMatrix[row][col];
printf("%d ", sumMatrix[row][col]);
}
printf("\n");
}
return 0;
}
void delete_matrix(int numRows, int** matrix){
int row;
for(row = 0 ; row < numRows; ++row){
free(matrix[row]);
}
free(matrix);
}
int main(){
int numRows, numCols;
int** matrix;
printf("Please Enter the number of rows: ");
scanf("%d", &numRows);
printf("Please Enter the number of cols: ");
scanf("%d", &numCols);
matrix = totalMatrix(numRows, numCols);
delete_matrix(numRows, matrix);
return 0;
}