只有数组的一个元素被传递给函数。 C++
Only one element of array is being passed into function. C++
出于某种原因,我的函数 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;
您的案例
想想执行吧。第一次它没有找到它立即 returns 并退出该功能。因此它只能看到一个元素。
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;
出于某种原因,我的函数 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;
您的案例
想想执行吧。第一次它没有找到它立即 returns 并退出该功能。因此它只能看到一个元素。
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;