传递给函数时,数组为空

Array empty when passed to function

本文关键字:数组 函数      更新时间:2023-10-16

我有下面的代码,正在做一个基于数组和值的二进制搜索,寻找传递给函数。然而,当我进入函数时,数组没有值。为什么会发生这种情况?我已经看过了,我相信在传递数组方面一切都是正确的。

 #include <iostream>
using namespace std;
int binSearch(int [], int , int , int);
void main()
{
    int a[10];
    int low;
    int high;
    int searchValue;
    for (int i = 0; i < 10; i++)
    {
        a[i] = i;           
    }
    low = 0;
    high = 9;
    searchValue = 6;
    int searchResult = binSearch(a, low, high, searchValue);
    cout << searchResult << endl;
}
int binSearch(int a[], int low, int high, int searchValue)
{
    int newHigh;
    newHigh = (low + high) / 2;
    if (low > high)
    {
        return -1;
    }
    else if (high == low)
    {
        if (a[high] == searchValue)
        {
            return high;
        }
        else
        {
            return -1;
        }
    }
    else if (a[newHigh] < searchValue)
    {
        return binSearch(a, low, newHigh, searchValue);
    }
    else
    {
        return binSearch(a, newHigh, high, searchValue);
    }
}

当你将一个数组传递给一个函数时,它被称为"衰减"为一个指针。c++中的数组是二等公民,无论何时将它们传递到某个地方,它们都会自动转换为指向第一个元素的指针。这意味着,当您检查函数内部的"数组"时,实际上查看的是第一个元素的值(因为数组衰减为指向第一个元素的指针)。

检查数组的一种方法是将其添加到监视窗口(右键单击-> add watch,或在监视窗口中键入变量名称),并在数组大小旁边加上逗号。

例如,在bin_search函数中,在watch窗口中输入a, 10,将显示a.

指向的前10个元素。

数组没有问题。main()在c++中应该返回int,并且二进制搜索算法需要修正。

#include <iostream>
using namespace std;
int binSearch(int [], int , int , int);
int main()
{
    int a[10];
    int low;
    int high;
    int searchValue;
    for (int i = 0; i < 10; i++)
    {
        a[i] = i;
    }
    low = 0;
    high = 9;
    searchValue = 6;
    int searchResult = binSearch(a, low, high, searchValue);
    cout << searchResult << endl;
    return 0;
}
int binSearch(int a[], int low, int high, int searchValue)
{
    int mid;
    mid = (low + high) / 2;
    if (low > high)
    {
        return -1;
    }
    if (a[mid] == searchValue)
    {
        return mid;
    }    
    else if (a[mid] < searchValue)
    {
        return binSearch(a, mid+1, high, searchValue);
    }    
    else
    {
        return binSearch(a, low, mid-1, searchValue);
    }
}

只管改int binSearch(int a[], int low, int high, int searchValue)

int binSearch(int* a, int low, int high, int searchValue)