我正在开展一个大型项目,我正在设计一个稀疏矩阵向量应用程序,但我仍在努力理解代码。我开始为应用程序构建基础,但在执行程序时遇到了分段错误。我在MatrixRead函数中跟踪了这个循环的问题,并将下面的代码括起来。当程序执行时,我尝试编写一些测试消息,程序似乎执行所有循环,但它最后返回分段错误。当然,这只是猜测。任何帮助都是极好的。谢谢!
while (ret != EOF && row <= mat->rows)
{
if (row != curr_row) // Won't execute for first iteration
{
/* store this row */
MatrixSetRow(mat, curr_row, len, ind, val);
/* check if the previous row is zero */
i = 1;
while(row != curr_row + i)
{
mat->lens[curr_row+i-1] = 0;
mat->inds[curr_row+i-1] = 0;
mat->vals[curr_row+i-1] = 0;
i++;
}
curr_row = row;
/* reset row pointer */
len = 0;
}
ind[len] = col;
val[len] = value;
len++;
ret = fscanf(file, "%lf %lf %lf", &r1, &c1, &value);
col = (int) (c1);
row = (int) (r1);
}
/* Store the final row */
if (ret == EOF || row > mat->rows)
MatrixSetRow(mat, mat->rows, len, ind, val);
这是MatrixSetRow函数的代码:
/*--------------------------------------------------------------------------
* MatrixSetRow - Set a row in a matrix. Only local rows can be set.
* Once a row has been set, it should not be set again, or else the
* memory used by the existing row will not be recovered until
* the matrix is destroyed. "row" is in global coordinate numbering.
*--------------------------------------------------------------------------*/
void MatrixSetRow(Matrix *mat, int row, int len, int *ind, double *val)
{
row -= 1;
mat->lens[row] = len;
mat->inds[row] = (int *) MemAlloc(mat->mem, len*sizeof(int));
mat->vals[row] = (double *) MemAlloc(mat->mem, len*sizeof(double));
if (ind != NULL)
memcpy(mat->inds[row], ind, len*sizeof(int));
if (val != NULL)
memcpy(mat->vals[row], val, len*sizeof(double));
}
我还包括Matrix.h文件的代码,其中定义了Matrix的成员:
#include <stdio.h>
#include "Common.h"
#include "Mem.h"
#ifndef _MATRIX_H
#define _MATRIX_H
typedef struct
{
int rows;
int columns;
Mem *mem;
int *lens;
int **inds;
double **vals;
}
Matrix;