I just wanted to comment on your question about accessing the array efficiently. You ask:
I was wondering if there are any more efficient ways to do what I'm currently doing (I'm really new to C and pointers/references in general) and without changing too much, getting
*(result.matrix+ i*r + j)to work like
result[i][j]
One way is to do as @mdfst13 has recommended and allocate an array of arrays. That's a fine way to do it, but it can be a performance issue when accessing the array element by element in a loop. CPUs generally optimize to access the next few bytes past the last access since you're likely to need bytes near the ones you previously accessed. If you have a separate array per row, this can throw off that optimization when you reach the end of each row. You'd want to first profile to verify that's an issue or not. If it is, another option you have is to leave it as a single allocation and simply write an accessor function. Something like:
long int getElement(const Matrix m, const int r, const int c)
{
return *(m.matrix + r * m.rowSize + c);
}
This also allows you the opportunity to do some range checking when in debug mode by doing something like:
long int getElement(const Matrix m, const int r, const int c)
{
#if DEBUG
assert((r >= 0) && (r < m.rowSize));
assert((c >= 0) && (c < m.colSize));
#endif
return *(m.matrix + r * m.rowSize + c);
}
(Or if you want to pass by referencea pointer in instead of passing by value, as suggested in mdfst13's answer, you could change the prototype to take a pointer to a Matrix and dereference the fields via pointer.)
Now when you want to access an element of the array, you would write:
long int x = getElement(result, i, j);
It's not as concise as just result[i][j], but it's better than writing out the math every time and potentially getting it wrong in some subtle way.