Return Error

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.

Thank you for your help!!

Last edited on
it says the variable row is uninitialized

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;
}

https://msdn.microsoft.com/en-us/library/84wcsx8x.aspx writes:
Standard behavior is to let a for loop's initializer [bar] go out of scope after the for loop [on line 4].

The line 6 should thus be an error.


// REQUIRES: mat points to a valid Matrix

If the mat were a reference and not a pointer, then it could never be an invalid pointer.
This makes so much sense but it doesn't work either. I'm still not getting the right answer.
Any idea why this wouldn't work???

1
2
3
4
5
6
7
8
9
// 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, const int* ptr) {

	int k = ptr - (mat->data);
	int row = k / (mat->width);
	return row;
}
Topic archived. No new replies allowed.