传递给函数时,数组为空
Array empty when passed to function
我有下面的代码,正在做一个基于数组和值的二进制搜索,寻找传递给函数。然而,当我进入函数时,数组没有值。为什么会发生这种情况?我已经看过了,我相信在传递数组方面一切都是正确的。
#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.
数组没有问题。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)
相关文章:
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 打印 2D 动态数组 c++ 函数
- C++数组函数
- 在数组函数指针中调用void
- 数组函数似乎没有找到最大值
- 使用数组函数和循环求解伪元编码|C
- 在头文件中的函数原型中获取指针数组:函数声明为 void
- 数组函数错误输出
- 读取文件,然后创建数组函数C++
- 指针数组函数参数-奇怪的行为
- 二维数组 - 函数
- "return"没有从数组函数返回正确的值
- 数组函数问题
- 数组函数的大小返回 int 的大小而不是数组
- 从数组函数中删除元素
- 如何从C++中最好地调用具有C99风格数组函数签名的函数
- 追加/打印/插入数组c++函数问题
- 如何将数组函数转换为指针函数
- 多维数组函数输出垃圾
- C++:数组函数的递归最大值