用零填充矩阵行的问题

Problem with fill matrix rows with zeroes

本文关键字:问题 填充      更新时间:2023-10-16

我必须检查给定矩阵是否具有与行相同的列,如果不是用零填充

我已经编写了代码,当行更大时它可以工作,但对于列,它显示核心转储

if(filas < cols){
//note filas means rows
//reserve of memory
int **nuevo = new int *[cols];
for(int i = 0; i < cols; i++)
nuevo[i] = new int [cols];

//start new matrix to 0
for(int i = 0; i < cols; i++){
for(int j = 0; j < cols; j++)
nuevo[i][j] = 0;
}
//copy original matrix to new
for(int i = 0; i < filas; i++){
for(int j = 0; j < cols; j++)
nuevo[i][j] = m[i][j];
}

filas = cols;
m = nuevo;
}


actual output:
1 2 3 4 
2 4 6 8 
3 6 9 12 
Segmentation fault (core dumped)
expected:
1 2 3 4 
2 4 6 8 
3 6 9 12 
0 0 0 0

当行大于列时:

original:
1 2 3  
2 4 6  
3 6 9  
4 8 12

output:
1 2 3 0 
2 4 6 0 
3 6 9 0 
4 8 12 0

问题在于行的初始化,这些行必须等于您main()中的 filas

改变

int filas = 3, cols = 4;
int **m = new int *[filas];
for(int i = 0; i < filas; i++)
m[i] = new int [filas];

int filas = 3, cols = 4;
int **m = new int *[cols];
for(int i = 0; i < cols; i++)
m[i] = new int [filas];

崩溃不是发生在llenar_0,而是发生在mainfilascols在传递给llenar_0时是引用,但m不是。 该函数创建nuevo,并将其分配给m,但该更改在返回时丢失,因此main尝试使用具有新大小的原始数组。

改变:

void llenar_0(int **m, int &filas, int &cols){

自:

void llenar_0(int ** &m, int &filas, int &cols){

如果你只想将给定的矩阵复制到方阵 -

int n = filas;
if ( filas < cols) {
n = cols;
}
int **nuevo = new int *[n];
for (int i = 0; i < n; ++i) {
nuevo[i] = new int [n];
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
nuevo[i][j] = 0;
}
}
for (int i = 0; i < filas; ++i) {
for (int j = 0; j < cols; ++j) {
nuevo[i][j] = m[i][j];
}
}

Nuevo是新的矩阵。希望这有帮助,谢谢