c++ - 只有数组的一个元素被传递给函数。 C++

标签 c++ arrays function pointers googletest

出于某种原因,我的函数 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 ?我不知道为什么它只将第一个值传递给函数。

最佳答案

你是第一次回来。

解决方案或提示

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;

关于c++ - 只有数组的一个元素被传递给函数。 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39782315/

相关文章:

c++ - 如何使用 taglib 检索/设置歌词?

javascript d3 从多重嵌套数组/对象数据集中获取最大值

arrays - 使用数组将 SharePoint Online 列表转换为 JSON

php - 我怎样才能输入这个数组

android - 使用函数参数按名称检索可绘制资源

javascript - 返回未定义的 Angular 服务不是函数

c++ - 爬取 Windows 程序菜单信息 C++

c++ - 使用线程编程

c++ - 当客户端关闭连接时 send() 不报告 ENOTCONN (AS400)

javascript - 在 JavaScript 中将带有参数的函数作为另一个函数的参数传递