2017-05-23 35 views
0

我必須在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; 
} 

然後給我一些測試程序:其中一半工作正常,另一個強硬給我段錯誤。我確信測試是正確的,所以在我的程序中一定有問題。你能幫我找到它嗎?

+1

「你能幫我找到它嗎?」。是的 - 建議您使用調試器。這是調試此類問題的最佳方法。 – kaylum

+0

這是我們的第二個課程,迄今爲止我們還沒有使用過調試器。我嘗試了valgrind,但它不是很有幫助 – user2704673

+0

調試器通常不是他們教的東西。這是你學習使用自己的工具。而且,儘早你學會了,因爲你的生活將來會更容易 –

回答

4

在循環

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;