只有一个数组元素被传递到函数中。C++

3
由于某些原因,我的函数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的引用吗?我不知道为什么它只传递函数中的第一个值。

1个回答

3
你是第一次返回。 解决方案或提示。
for (int i = 0; i < size; i++) {
    if (key == theArray[i])
        return (theArray);
    //if it cannot find it the very first time, it returns null IN YOUR CASE :)
}
return nullptr;

你的情况

只需考虑执行过程。第一次未找到某个东西时,它立即返回并退出函数。因此,它只看到一个元素。

for (int i = 0; i < size; i++) {
        if (key == theArray[i])
            return (theArray);
        else
            return nullptr;
    }

更新

for (int i = 0; i < size; i++) {
    if (key == theArray[i])
        return (theArray + i); 
    // you currently pass the pointer to the start of the array again and again. Pass the pointer to the element instead.
}
return null;

嗯,现在我离成功更近了,但还不够。我把 return nullptr 移到了数组外面,并添加了这一行:else if (key != theArray[i]) continue;,但它仍然失败了……只是没有返回 null。 - WitchKing17
从这里有什么想法吗? - WitchKing17
首先,你应该返回 (theArray + i)。(theArray) 只返回一个指向数组开头的指针,而这个指针你已经有了。你不需要额外的 else 语句。请查看更新部分。 - Abhirath Mahipal
1
哦,我不知道为什么我从来没有想到过那个。+1 谢谢你,你帮助我理清了思路! - WitchKing17
没问题。指针也让我困扰了很久。如果你想知道我如何变得更好(我还是个初学者),请随时与我联系 :) - Abhirath Mahipal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接