简体   繁体   中英

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 . The test case I have is the following (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:

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? 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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