【问题标题】:Matrix copying causes segmentation fault矩阵复制导致分段错误
【发布时间】:2017-05-23 20:59:38
【问题描述】:

我必须用 C 语言编写一个函数,它接受一个矩阵 (src) 和 2 个整数值 (x,y),然后给出一个包含 src x y 次的矩阵。 例如

3 5
2 1

与 (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

我得到了结构

struct Mat {
  int cols; // number of columns
  int rows; // number of rows
  int** row_ptrs; // pointer to rows (the actual matrix)
} Mat;

并写了这个函数:

#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;
}

然后我得到了一些测试程序:其中一半工作正常,另一个艰难给了我段错误。我确定测试是正确的,所以我的程序肯定有问题。你能帮我找到吗?

【问题讨论】:

  • “你能帮我找到它吗?”。是的 - 建议您使用调试器。这是调试此类问题的最佳方式。
  • 这是我们的第二门课程,到目前为止我们还没有使用过调试器。我尝试了 valgrind,但它不是很有帮助
  • 调试器通常不是他们教的东西。它是您正在学习自己使用的工具。越早学会,以后的生活就会越轻松
  • i &lt; newMat-&gt;cols --> i &lt; newMat-&gt;rows
  • @BLUEPIXY,你再一次给出了正确的答案,但是在 cmets 中,太棒了! =)

标签: c pointers segmentation-fault


【解决方案1】:

循环中的条件

  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++)
                     ^^^^^^^^^^^
    newMat->row_ptrs[i] = calloc(newMat->cols, sizeof(int));

注意:我认为你的意思是

typedef struct Mat {
^^^^^^^
  int cols; // number of columns
  int rows; // number of rows
  int** row_ptrs; // pointer to rows (the actual matrix)
} Mat;

【讨论】:

    猜你喜欢
    • 2011-11-22
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-14
    • 2016-05-28
    • 1970-01-01
    相关资源
    最近更新 更多