PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, June 25, 2022

[FIXED] When I am pass the array as arguments then I am faceing this error invalid types 'int[int]' in c++

 June 25, 2022     arrays, c++, compiler-errors, function-declaration     No comments   

Issue

I am new to c++. can anyone guide me on how I can pass the array in functions?

basically, I am trying to find a number with a linear search and print the index of that number in 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;
    }

this is the error

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);
                                  ^

Solution

For starters variable length arrays like this

int  arr[size];

is not a standard C++ feature. Instead it would be much better to use the standard container std::vector<int> in a C++ program.

Secondly the function declaration is incorrect. The first parameter is declared as having the type int.

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

You need to declare the function the following way

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

or equivalently

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

Pay attention to that there is standard algorithm std::find in C++ that performs searching an element in a container.



Answered By - Vlad from Moscow
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing