Array doesnt accept more than 6 values

I wrote a simple code to search an element in an array that can be input by the user. However, the array does not take more than 6 values.
Here is the code. (It still isnt complete)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include<iostream>
using namespace std;
void search( int item[], int size, int object);
int main()
{
  int i, elements[i], size, obj;
  cout<<"Enter the number of elements: ";
  cin>>size;
  cout<<endl;
  for(i=0; i<=size; i++)
    {
      cin>>elements[i];
     
    }
  for(i=0; i<=size; i++)
    {
      cout<<elements[i]<<" ";
    }
  cout<<endl;
  cout<<"Enter the element to search: ";
  cin>>obj;
  search( elements, size, obj);

  return 0;
}
void search(int item[], int size,  int object)
{
  int k, key;
  for(k=0; k<size; k++)
    {
      key= item[k];
      if(key== object)
	{
           cout<<"The element is in "<<k+1<<" place.";
	   break;
         }
      //else if( 
    }
}


Where have I gone wrong?
Line 6: how many elements does the array have?
At least two errors here:
 
    int i, elements[i]

i is not initialised, so it can contain any garbage value.
The number of items in the array elements must be a constant, known at compile time. You tried to use a variable, which is not valid in C++, and of course it is also invalid since the variable was not initialised.

It should look something like this:
1
2
const int size = 100; // set required number of elements in array.
int elements[size];   // array dimension is a constant known at compile time. 

If you want a variable sized array, decided at runtime, use a vector (or dynamically allocate using new []).
So, there is no other way than vector by which I can create an array whose length is decided at runtime?
Last edited on
The std::vector is good to learn regardless, but it definitely is a good container for your program. Standard library has other containers too.

Chervil did mention explicit dynamic allocation:
1
2
3
4
5
size_t size;
if ( std::cin >> size ) {
  std::unique_ptr<int[]> elements (new int[size]);
  // use elements
}

See http://www.cplusplus.com/reference/memory/unique_ptr/operator%5B%5D/
So, there is no other way than vector by which I can create an array whose length is decided at runtime?

It's non-standard but I believe the gnu C++ compiler will let you define an array whose size is an expression. Actually if your code compiled then you're using a compiler with this extension. All you would need to do is move the definition of elements and give it the right size:
1
2
3
4
5
  int i, size, obj;
  cout<<"Enter the number of elements: ";
  cin>>size;
  cout<<endl;
  int elements[size];
Topic archived. No new replies allowed.