由于某些原因,我的函数
LinearSearch
只获取传入的数组的第一个元素。我在函数中设置了断点并查看了它所具有的本地变量,发现它为什么只从数组a
中获取7
。我拥有以下测试用例(GoogleTest):TEST(LinearSearch, ElementExists2Items) {
// LinearSearch should return a pointer to the item if it exists in the array.
int a[2] = {7, 2};
EXPECT_EQ(a, LinearSearch(a, 2, 7));
EXPECT_EQ(a + 1, LinearSearch(a, 2, 2));
}
这是我的LinearSearch
函数:
int* LinearSearch(int theArray[], int size, int key) {
if (size == 0)
return nullptr;
for (int i = 0; i < size; i++) {
if (key == theArray[i])
return (theArray);
else
return nullptr;
}
}
我是否漏掉了什么?我需要传递theArray
的引用吗?我不知道为什么它只传递函数中的第一个值。
return nullptr
移到了数组外面,并添加了这一行:else if (key != theArray[i]) continue;
,但它仍然失败了……只是没有返回 null。 - WitchKing17