【问题标题】:argument of type “int” incompatible with parameter of type “int*”“int”类型的参数与“int*”类型的参数不兼容
【发布时间】: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 &lt; a[100] 中的未定义行为,因为您索引数组超出范围(您的意思是 i &lt; 100?)。 3) 考虑向good C++ book学习。
  • @KenWhite "a[100] is the 100th" 它是索引 100 处的元素,我们称之为第 101 个
  • @curiousguy:你是对的,当然。 :-)

标签: c++


【解决方案1】:

在 main() 中的 for() 循环之后,你需要这样的东西:

cout << "Enter the value to search for: ";
cin >> x; 

wait = searchArray(a, x);

cout << x;
cout << " is at position: ";
cout << wait;

【讨论】:

    【解决方案2】:
    int searchArray(int a[], int x) 
    {
        for (int i = 0; i < 100; i++) //change a[100] to 100 because it only needs the size not the array itself
        {
            if (x == a[i])
                return i + 1;
            break;
        }
        return -1;
    }
    
    int main()
    {
        int wait, x, y, a[100];
    
        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];
        }
    
        cout<<"Number to look for: "; //sets a value for x
        cin>>x;
    
        cout<<"Index: "<<searchArray(a, x)<<endl; //function returns an int therefore a cout is needed
    
        cin >> wait;
    
        return 0;
    }
    

    【讨论】:

    • 请添加上下文和解释。仅代码不是答案
    猜你喜欢
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多