'error: invalid types 'int[int]' for array subscript in c++
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 1:[1]
First in C++, the size of an array must be a compile-time constant.So, take for example the following code snippets:
int n = 10;
int arr[n]; //INCORRECT because n is not a constant expression
The correct way to write the above would be:
const int n = 10;
int arr[n]; //CORRECT
Similarly, the following(which you did in your code example) is incorrect:
int size;
int temp;
cout << "Enter Size of Arry";
cin >> size;
int arr[size];//INCORRECT because variable size is not a constant expression
You should use std::vector for your purpose as shown below:
#include <iostream>
#include <vector>
using namespace std;
//the first argument is a vector<int>
int search(std::vector<int> arr, int x)
{
int i=0;
for (i = 0; i < arr.size(); i++){//use size()member function
if (arr[i] == x){
return i;}
}
return -1;
}
// Driver code
int main(void)
{
int size;
int temp;
cout << "Enter Size of Arry";
cin >> size;
//create a vector instead of an array
std::vector<int> arr(size);
for(int i=0;i<arr.size();i++){//use the size member function
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, x);//no need to pass the size of the vector
(result == -1)
? cout << "Element is not present in array"
: cout << "Element is present at index " << result;
return 0;
}
Note that you can also use std::find instead of writing your own search algorithm.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anoop Rana |
