axe_flame_37
axe_flame_37

Reputation: 11

Why does my C program for linear algebra fail with non-square matrices?

I am creating a set of linear algebra functions in C, just for practice; I define a matrix as a struct storing the number of rows and columns, and a double pointer to access the values (I'm only supporting matrices of doubles at the moment).

The basic functions for constructing a then printing a matrix instance work fine with square matrices, but when I try to build and print a non-square (number of rows is not equal to number of columns) matrix the program crashes. Note that I am using codeblocks on Windows 10 Home.

Here is a piece of code that is sufficient to replicate the problem:

#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("%.1f\n", *ePoint);
    ePoint = ePoint + cellsize;
    }

return 0;

}

The error I get is "Process returned -1073740940 (0xC0000374)"

Upvotes: 1

Views: 59

Answers (1)

4386427
4386427

Reputation: 44329

This is wrong:

ePoint += cellsize;  

because cellsize is equal to sizeof(double)

Instead use

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

To move to the next element of the array, the pointer shall only be incremented by one - do not increment with the size of the element.

Likewise for:

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

Upvotes: 2

Related Questions