When you call
unitUnderTest.findEmptySpace(*row, 4)
the expression row
will decay to a pointer to the first element of row
, i.e. to &row[0]
. Therefore, the expression *row
is equivalent to row[0]
, which is a pointer to the variable o
, i.e. a pointer to a single character.
In the function Widget::findEmptySpace
, in the following loop, you use this pointer to a single character as if it were a pointer to 4 characters:
for(int i = 0; i < size; i++) {
cout << row[i];
}
Since the function argument row
(in contrast to the original array with that name) is a pointer to a single character, the only valid index for row
would be row[0]
. However, you are using the indexes row[0]
to row[3]
, so you are accessing the object out of bounds, causing undefined behavior.
The function signature
int Widget::findEmptySpace(char row[], int size)
is probably not what you want. If you want to pass a pointer to the entire array row
from the functon TEST
to the function findEmptySpace
, then you should pass a pointer to the first element of the array as well as its length. You are already doing the latter properly, but you are not doing the former properly. Since every element of the array is of type char *
, a pointer to the first element of the array would be of type char **
, i.e. a pointer to a pointer. Therefore, you should change the function signature to the following:
int Widget::findEmptySpace( char **row, int size )
Or, if you prefer, you can use this equivalent, to make it clear that the higher level pointer points to an array:
int Widget::findEmptySpace( char *row[], int size )
Of course, you will have to rewrite your function findEmptySpace
to adapt to the different parameter type, so that it dereferences the pointer:
int Widget::findEmptySpace( char *row[], int size )
{
cout << "The row under test is:\n";
for( int i = 0; i < size; i++ ) {
cout << *row[i];
}
cout << "\n";
for( int i = 0; i < size; i++ ) {
if( *row[i] == WHITE_SPACE ) {
return i;
}
}
return -1;
}
Now, in the function TEST
, you must change the way you are calling the function findEmptySpace
, due to the changed function parameter. You should change the lines
EXPECT_EQ(unitUnderTest.findEmptySpace(*row, 4), 0);
EXPECT_EQ(unitUnderTest.findEmptySpace(*row2,4 ), 1);
to:
EXPECT_EQ(unitUnderTest.findEmptySpace( row, 4), 0);
EXPECT_EQ(unitUnderTest.findEmptySpace( row2, 4 ), 1);
Now you are no longer passing the value of the first array element, but you are instead passing a pointer to the first array element, so that the function findEmptySpace
can access the entire array properly.