gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:14:48 24 4
gpt4 key购买 nike

出于某种原因,我的函数 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com