为什么我的线性代数C程序在处理非平方矩阵时失败了



我正在用C创建一组线性代数函数,只是为了练习;我将矩阵定义为存储行数和列数的结构,以及访问值的双指针(目前我只支持双精度矩阵(。

构造然后打印矩阵实例的基本函数适用于方形矩阵,但当我尝试构建和打印非方形(行数不等于列数(矩阵时,程序会崩溃。请注意,我在Windows10Home上使用代码块。

以下是一段足以复制问题的代码:

#include <stdio.h>
#include <stdlib.h>
const int cellsize = sizeof(double);
typedef struct{
int rows;
int columns;
double *elements;
}pMatrix;

int main()
{
pMatrix test;
int cellcount;
double test_values[] = {3.0, -4.0, 0, 0, 4.0, 3.0};
double* ePoint;
test.columns = 3;
test.rows = 2;
cellcount = test.columns*test.rows;
test.elements = malloc(test.columns*test.rows*cellsize); //Allocate memory
ePoint = test.elements;
for(int i = 0; i < cellcount; i++){ //Read in values
*ePoint = test_values[i];
ePoint += cellsize;
}
printf("Values:n");
ePoint = test.elements; //Print out values
for(int i = 0; i < cellcount; i++){
printf("%.1fn", *ePoint);
ePoint = ePoint + cellsize;
}
return 0;
}

我得到的错误是";进程返回-1073740940(0xC0000374(";

这是错误的:

ePoint += cellsize;  

因为cellsize等于sizeof(double)

而是使用

ePoint += 1;   (or ++ePoint;)

要移动到数组的下一个元素,指针只能增加一个-不要随元素大小增加。

同样适用于:

ePoint = ePoint + cellsize; --> ePoint = ePoint + 1; (or ++ePoint;)

最新更新