[英]Matrix copying causes segmentation fault
I must write a function in C that takes in a matrix (src) and 2 integer values(x,y), then gives out a matrix which contains src x by y times. 我必须用C编写一个函数,该函数接受一个矩阵(src)和2个整数值(x,y),然后给出一个包含src x乘以y倍的矩阵。 For example 例如
3 5
2 1
with (2,3) is going to be 与(2,3)将会是
3 5 3 5
2 1 2 1
3 5 3 5
2 1 2 1
3 5 3 5
2 1 2 1
I am given the structure 我得到的结构
struct Mat {
int cols; // number of columns
int rows; // number of rows
int** row_ptrs; // pointer to rows (the actual matrix)
} Mat;
and wrote this function: 并写了这个函数:
#include "exercise_1.h"
#include <stdlib.h>
Mat* matrixRepeat(Mat* src, int num_row_blocks, int num_col_blocks)
{
Mat *newMat = malloc(sizeof(Mat));
newMat->rows = src->rows * num_row_blocks;
newMat->cols = src->cols * num_col_blocks;
newMat->row_ptrs = calloc(newMat->rows, sizeof(int*));
for(int i = 0; i < newMat->cols; i++)
newMat->row_ptrs[i] = calloc(newMat->cols, sizeof(int));
for(int i = 0; i < newMat->rows; i++)
for(int j = 0; j< newMat->cols; j++)
newMat->row_ptrs[i][j] = src->row_ptrs[i%src->rows][j%src->cols];
return newMat;
}
Then I am given some test programs: half of them works just fine, the other tough gives me segfault. 然后给我一些测试程序:其中一半工作正常,另一项艰难使我断断续续。 I know for sure that the tests are correct, so there must be a problem in my program. 我肯定知道测试是正确的,所以程序中肯定有问题。 Can you help me find it? 你能帮我找到它吗?
The condition in the loop 循环中的条件
for(int i = 0; i < newMat->cols; i++)
^^^^^^^^^^^
newMat->row_ptrs[i] = calloc(newMat->cols, sizeof(int));
is wrong. 是错的。 There must be 必须有
for(int i = 0; i < newMat->rows; i++)
^^^^^^^^^^^
newMat->row_ptrs[i] = calloc(newMat->cols, sizeof(int));
Note: I think you mean 注意:我认为你的意思是
typedef struct Mat {
^^^^^^^
int cols; // number of columns
int rows; // number of rows
int** row_ptrs; // pointer to rows (the actual matrix)
} Mat;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.