Plutonium smuggler
Plutonium smuggler

Reputation: 339

Program stuck in loop

I have a very simple program which is given below. I have inserted couts to know which line gets executed.

int main(void) {
  int n_in = 0;
  int keys = 0;
  cin>>n_in;
  long long in_array[n_in];

  for(int i=0; i<n_in; i++){
    cin>>in_array[i];
  }
  cout<<"Executed"; 
  cin>>keys;
  cout<<"Executed"<<" "<<keys;
  int index[keys];
  long long key_array[keys];
  cout<<"Executed";
  for(int j=0; j<keys; j++){
    cin>>key_array[j];
    cout<<"Iteration" <<j<<"complete" ;
  }
  cout<<"Executed";
  //bin_search(in_array, n_in, key_array, keys, index);

  for(int i=0; i<keys; i++){
    cout<<index[i]<<" " ;
  }
  return 0;

}

The screenshot is given:

enter image description here

As you can see from the image, the last iteration never completes and I don't know why. The numbers after iteration0complete etc. are inputs.

Can someone please explain whats happening?

Upvotes: 0

Views: 286

Answers (1)

Mourad
Mourad

Reputation: 474

Here is a modified version of your code, as mentioned in the comments i used vectors instaed of arrays, because you can use vector without knowing the size of it, which is the opposite of declaring arrays, at compile time the compiler must know the size of the array, but you define an array and you give it a size which is not a constant at compile time, i commented the part of the code where you use the array index[] because i dont know why you are printing what the array has, while it is empty, you dont have anything inside it you just declared it.

here is the code hope it fulfill your needs.

#include<string>
#include<vector>
#include<iostream>



using namespace std;


int main(){


    int n_in = 0;
  int keys = 0;
  cin>>n_in;
  vector<long long> in_array;

  for(int i=0; i<n_in; i++){
      int k =0;
      cin >> k;

    in_array.push_back(k);
  }
  cout<<"Executed"; 
  cin>>keys;
  cout<<"Executed"<<" "<<keys;

  vector<int> index;
  vector<long long> key_array;
  cout<<"Executed";

  for(int j=0; j<keys; j++){
      int p =0;

    cin>>p ;
        key_array.push_back(p);
    cout<<"Iteration" <<j<<"complete" ;
  }
  cout<<"Executed";
  //bin_search(in_array, n_in, key_array, keys, index);

  /*for(int i=0; i<keys; i++){
      int m =0;

    cout<<index[i]<<" " ;
  }
*/

    return 0;
}

Edit: What you said in the comment is true in C, but in c++ the compiler need to have the exact size of the array when compiling, otherwise you will have to use the new operator to dynamically allocate memory.

For example:

int MyArray[5]; // correct

or

const int ARRAY_SIZE = 6;
int MyArray[ARRAY_SIZE]; // correct

but

int ArraySize = 5;
int MyArray[ArraySize]; // incorrect

To sum it up:

The number of elements of an array, must be a constant expression . If you need variable bounds, use a vector.

Upvotes: 1

Related Questions