用零填充矩阵行的问题
Problem with fill matrix rows with zeroes
我必须检查给定矩阵是否具有与行相同的列,如果不是用零填充
我已经编写了代码,当行更大时它可以工作,但对于列,它显示核心转储
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
,而是发生在main
。filas
和cols
在传递给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是新的矩阵。希望这有帮助,谢谢
相关文章:
- C++ 填充数组时遇到问题
- 将十六进制值设置为用于填充的字符变量时出现问题
- 我想直接在结构中插入,但没有一种方法可以正确避免填充问题
- 使用初始化列表填充C++中的多维结构数组时出现问题
- 使用队列和列表 STL 进行C++分配。在将数据填充到列表或队列中然后打印该数据时遇到问题
- 在使用结构体和用函数填充其变量(使用指针)时遇到问题
- 用零填充矩阵行的问题
- BMP文件行填充问题
- 按行、列或随机从数组填充矩阵时出现错误索引问题
- 清除并重新填充 std::vector<std::vector<T>>导致分配问题
- 填充 c++ 数组时遇到问题,每个索引处只有最后一项
- 尝试递归填充和打印出两组的所有归纳函数的问题
- 这个简单的木炭填充器有什么问题
- 在检查现有元素时,从文件填充并行数组时出现问题
- 填充动态类模板数组时遇到问题
- 使用__declspec的内存填充问题
- 使用 C++11 的 std::regex 填充子匹配时遇到问题
- c++填充数组问题
- 长哈希填充问题
- 内存填充问题