I just can't get this function to work. Right now it won't compile. I just cannot figure out why it says the variable row is uninitialized. Am I doing the pointer comparison wrong?
By the way the code below compiled but did not return the correct value.
Consider the case, where the if condition is never true. On such call the function is effectively this:
int Matrix_row( const Matrix*, const int* ) {
int row;
// waste some cpu cycles
return row ;
}
What was the value that the function returns? Uninitialized. Undefined.
You have type class Matrix. Why do you have to do index math? Why the Matrix does not have a function for it?
It does seem that a Matrix has a one-dimensional array, but represents a 2-D array.
If the ptr is a pointer to element k in mat->data, then ptr == mat->data + k
In other words, auto k = ptr - mat->data; and you can calculate the row from k.
mat->data + mat->width * r + c == mat->data + k
=>
mat->width * r + c == k
=>
mat->width * r == k - c
=>
r = k / mat->width - c / mat->width
=>
r = k / mat->width
the code below compiled
Really? Is this legal, and if yes, what does it return?
1 2 3 4 5 6 7
int foo()
{
for ( int bar = 0; bar < 7; ++bar ) {
}
return bar - 1;
}
// REQUIRES: mat points to a valid Matrix
// ptr points to an element in the Matrix
// EFFECTS: Returns the row of the element pointed to by ptr.
int Matrix_row(const Matrix* mat, constint* ptr) {
int k = ptr - (mat->data);
int row = k / (mat->width);
return row;
}