tags:

views:

217

answers:

1

I need to implement operations with matrices and size of matrix has to be variable. The only solution I came up with is to use linked list:

[pointer to this row, pointer to another row] -> [element 1,1; link to another element] -> [element 1,2,  link to another element] -> .... -> [nil]
     |
     v
[pointer to this row, pointer to another row] ...
     ...

But it seems to me a little bit complex.. Is there a better (and easier) solution?

Thank you guys!

+1  A: 

One approach would be to use GetMem to allocate exactly enough memory. GetMem seems widely supported.

const
    MAXMATRIXDATA: Word = 10000;
type
    TMatrixDataType = Word;
    TMatrixData = array[0..MAXMATRIXDATA] of TMatrixDataType;
    PMatrixData = ^TMatrixData;
    TMatrix = record
     Rows, Cols: Word;
     MatrixData: PMatrixData;
     end;
    PMatrix = ^TMatrix;

function CreateMatrix(Rows, Cols: Word): PMatrix;
var
    Ret: PMatrix;
begin
    New(Ret);
    Ret^.Rows := Rows;
    Ret^.Cols := Cols;
    GetMem(Ret^.MatrixData,Rows*Cols*SizeOf(TMatrixDataType));
    CreateMatrix := Ret;
end;

function GetMatrixData(Matrix: PMatrix; Row, Col: Word): TMatrixDataType;
begin
    GetMatrixData := Matrix^.MatrixData^[(Row*Matrix^.Cols)+Col];
end;

procedure SetMatrixData(Matrix: PMatrix; Row, Col: Word; Val: TMatrixDataType);
begin
    Matrix^.MatrixData^[(Row*Matrix^.Cols)+Col] := Val;
end;
Will
MAXMATRIXDATA: Word = 10000; doesn't work in FreePascal => MAXMATRIXDATA = 10000 works
MartyIX