数组中目标的返回地址

时间:2018-12-07 12:18:01

标签: c++ function pointers for-loop

我无法识别我的错误。我需要创建一个函数int search (int *p, int s, int n),该函数将在数组中搜索目标,如果找到它,它将返回地址,但是如果找不到,它将返回NULL

#include <iostream>
using namespace std;

int search(int *p , int s, int n)
{
    for(int i = 0; i < s; i++)
    {
        if(*p == n)
            return &p;
        p++;
    }

    return NULL; 
}

int main()
{
    int n;
    int arr[6] = {1, 2, 3, 4, 5, 6};

    cout << "Enter target: "<< endl;
    cin >> n;

    cout << search(arr, 6, n) << endl;

    return 0;
} 

3 个答案:

答案 0 :(得分:0)

返回&p绝对是错误的。 p是一个函数参数,其寿命不会超过其函数的结尾。在常见的实现中,它驻留在堆栈中,并在返回时消失,或更确切地说,可以在函数返回后的任何时间覆盖它。

但是您不需要。如果需要整数索引,则需要:

return i;

如果您真的想要一个地址,则应该具有:

int* search ( int *p , int s, int n)        // returns an int* not an int
{
    for(int i = 0; i<s;i++)
    {
        if(*p==n)
        return p;
       p++;
    }
    return NULL;  // you should return a defined value if not found
}

答案 1 :(得分:0)

#include <iostream>
#include <memory>
#include <algorithm>
#include <vector>

void findItemInVec(std::vector<int> &v ,int number) {
    std::for_each(v.begin(), v.end(), [number](int &item_in_vec) ->void {
        if (item_in_vec == number) {
            std::cout << &item_in_vec << std::endl;
        }
    });
}


int main()
{   
    std::vector<int> v{ 1,2,5,8,7,6,1 };

    findItemInVec(v, 1);
    return 0;
}

函数中的参数是整数值的向量。函数std :: for_each使用迭代器help检查向量中的每个项目,并使用number参数检查其值是否相同。对于每笔返回true的支票,它都会键入此项的地址。

答案 2 :(得分:0)

您快到了:

return &p;

这是您遇到的问题:您正在返回用于迭代输入数组的本地指针的地址。

由于您在代码中使用了if(*p == n),所以我想您已经知道p已经是一个指针。然后,一旦找到该元素,您应该立即将其返回:

return p;