【发布时间】:2019-03-29 22:24:39
【问题描述】:
目标是搜索数组并在其中找到特定的数字并返回位置。我有如何做到这一点的方法,但试图让它在 main 方法中运行却给了我标题中的错误。我该怎么做才能解决?
#include "stdafx.h"
#include <iostream>
using namespace std;
int searchArray(int a[], int x) {
for (int i = 0; i < a[100]; i++) {
if (x == a[i])
return i + 1;
break;
}
return -1;
}
int main()
{
int wait, x, y, a[100];
//problem 3
cout << "Enter the size of the array(1-100): ";
cin >> y;
for (int i = 0; i < y; i++) {
cout << "Enter an array of numbers:";
cin >> a[i];
}
searchArray(a[100], x); //i get error on this line with a[100]
cin >> wait;
return 0;
}
预计它应该没有错误地运行并在数组中找到一个数字的位置,但我只是得到错误并且无法运行它。
【问题讨论】:
-
函数期望第一个参数是指针,但您正在向它传递值。此外,值 x 未初始化。
-
int是一个整数。int *是一个指针。你没有传递一个指针。a[100]是 int 数组a的第 100 个元素,而不是数组本身。 -
@Chaos_warfare24 1) 您可以通过将指针传递给第一个数组元素而不是越界数组元素来修复即时错误:
searchArray(a, x);2) 您会遇到的下一个问题是i < a[100]中的未定义行为,因为您索引数组超出范围(您的意思是i < 100?)。 3) 考虑向good C++ book学习。 -
@KenWhite "a[100] is the 100th" 它是索引 100 处的元素,我们称之为第 101 个
-
@curiousguy:你是对的,当然。 :-)
标签: c++