Anolethron wrote On 07/18/07 13:32,:
Wrong one:
void minptr (int *matrix, int rows, int columns,int *min){
int i=0,j=0;
*min=*matrix; //!!!!!!!!!!!!!!! !!
for (i=0; i < rows; i++) {
for (j=0; j < columns; j++) {
if( *min *(matrix+(i*col umns)+j) ) {
min = (matrix+(i*colu mns)+j);
}
}
}
}
Right one:
int* minptr2 (int *matrix, int rows, int columns){
int i=0,j=0;
int *min=matrix;
for (i=0; i < rows; i++) {
for (j=0; j < columns; j++) {
if( *min *(matrix+(i*col umns)+j) ) {
min = (matrix+(i*colu mns)+j);
}
}
}
return min;
};
These functions are supposed to give the pointer to the minimal element
of a 3x4 matrix. It is claimed that the first one is wrong because it
calls "min" by value. Can anyone make it clear why the first one is
wrong and the second one is right?
The first version would be called like this:
int mat[3][4] = ...;
int minimum;
minptr(&mat[0][0], 3, 4, &minimum);
However, the only "externally visible" effect of the
call would be the same as if you had written
minimum = mat[0][0];
The line with all the exclamation points copies the
matrix' first value to the variable that min points
to -- that is, to minimum in the caller. Thereafter,
nothing that happens inside minptr has any effect on
the caller. When a function changes the value of one
of its own arguments, it's only changing its own local
copy of that value, so all the adjustments to `min'
that go on inside the function remain unseen outside.
The second function sets up and probably makes
changes to its own local variables, and these changes
are also invisible from outside. However, the second
function returns a copy of one of those variables as
its own function value. You would call it like this:
int mat[3][4] = ...;
int *smallest;
smallest = minptr2(&mat[0][0], 3, 4);
The caller can't actually see the variable min inside
minptr2 -- in fact, by the time minptr2 returns, min
doesn't even exist any more -- but the value that was
stored in that variable is now stored in smallest
because it was returned as the function value.
Plus, inthe second one, min points to
a pointer (matrix) how can the line *min *(matrix+(i*col umns)+j) make
sense then? How can you confront the value of a pointer with the value
in the matrix?
(I think that by "confront" you mean what a native
English speaker would call "compare.")
Notice the `*' operators at the start of the expression
on each side of the comparison. Simplified, it looks like
*a_pointer *another_pointe r
.... and this doesn't compare the pointers, but the things
that they point to. `min' points to some element of the
matrix, `(matrix+(i*col umns)+j)' points to a different
element (except on the very first time through the loop,
when they both point to the [0][0] element), and the
comparison checks whether one element is larger than the
other. The pointers just indicate where the things to be
compared are; the pointers themselves are not compared.
--
Er*********@sun .com