c++ - 当我将数组作为参数传递时,我遇到此错误 invalid types 'int[int]' in c++

标签 c++ arrays compiler-errors function-declaration

我是 C++ 新手。谁能指导我如何在函数中传递数组?

基本上,我试图通过线性搜索找到一个数字并在 C++ 中打印该数字的索引

   // linear search 
    #include <iostream>
    using namespace std;
    
    int search(int arr, int n, int x)
    {
        int i=0;
        for (i = 0; i < n; i++){
            if (arr[i] == x){
                return i;}
        }
        return -1;
    }
    
    // Driver code
    int main(void)
    {
        int size;
        int temp;
        cout << "Enter Size of Arry";
        cin >> size;
        int  arr[size];
        for(int i=0;i<size;i++){
            cout << "Enter a " << i << "Element of your arry : ";
            cin >> temp;
            arr[i]=temp;
    
        }
        
    
         cout << "Enter the number that you will find index";
            int x;
         cin >> x;
        // Function call
        int result = search(arr, size, x);
        (result == -1)
            ? cout << "Element is not present in array"
            : cout << "Element is present at index " << result;
        return 0;
    }

这是错误

Q1.cpp: In function 'int search(int, int, int)':
Q1.cpp:9:12: error: invalid types 'int[int]' for array subscript
   if (arr[i] == x){
            ^
Q1.cpp: In function 'int main()':
Q1.cpp:35:34: error: invalid conversion from 'int*' to 'int' [-fpermissive]
  int result = search(arr, size, x);
                                  ^

最佳答案

对于初学者来说,像这样的可变长度数组

int  arr[size];

不是标准 C++ 功能。相反,使用标准容器 std::vector<int> 会更好。在 C++ 程序中。

其次,函数声明不正确。第一个参数被声明为 int 类型。

int search(int arr, int n, int x)

您需要按以下方式声明该函数

int search(int arr[], int n, int x)

或者同等的

int search(int *arr, int n, int x)

注意有标准算法std::find在 C++ 中执行搜索容器中的元素。

关于c++ - 当我将数组作为参数传递时,我遇到此错误 invalid types 'int[int]' in c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70133171/

相关文章:

c++ - 检测鼠标按钮是否按下

c++ - C++ 中的内存屏障示例有哪些?

php - 将数组转换为关联数组

c++ - 从函数返回一个shared_ptr

c++ - 调试在 dllhost.exe 中运行的 inproc com 服务器

java - O(n) 算法在从 1 到 n(不是奇数)的连续整数数组中找到奇数输出

php - 删除 php 数组中的空项

android-studio - 片段数据绑定(bind),DataBinderMapperImpl.java 找不到符号 FragmentCollectionBindingImpl

Android源代码编译问题

haskell - Haskell非类型变量参数错误