简体   繁体   English

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

[英]Only one element of array is being passed into function. C++

For some reason, my function LinearSearch is only getting the first element of the array that's being passed in. I found this by putting a breakpoint in the function and looking at the locals that it has, and I don't know why it's only getting the 7 from the array a . 出于某种原因,我的函数LinearSearch只获取了传入的数组的第一个元素。我通过在函数中放置一个断点并查看它所拥有的本地元素来发现这一点。我不知道为什么它只会得到它数组中的7 a The test case I have is the following (GoogleTest): 我的测试用例如下(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));
}

Here is my LinearSearch function: 这是我的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;
    }
}

Am I missing something? 我错过了什么吗? Do I need to pass theArray by reference instead? 我需要通过引用传递theArray吗? I don't know why it's only getting the first value passed into the function. 我不知道为什么它只是将第一个值传递给函数。

You are returning the very first time. 你是第一次回来。

Solution or rather a hint 解决方案或者说是一个提示

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;

Your Case 你的案子

Just think about the execution. 试想一下执行情况。 The very first time it does not find something it immediately returns and exits the function. 它第一次没有找到它立即返回并退出该功能。 Hence it only sees one element. 因此它只看到一个元素。

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

Update 更新

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM