C++ Code is working fine on other platform but not on Repl

Question: I have written a code for sorting 0s, 1s and 2s in an array in C++. The code is working fine on other online IDE and on VScode but don’t know why it is not working on Replit.

Repl link: https://replit.com/@amanraiii/sortingArray#main.cpp

#include<iostream>
using namespace std;

void printArray(int arr[], int size){

  for(int i = 0; i < size; i++){
    cout << arr[i] << " ";
  }
  cout << endl;
}

void sortArray(int arr[], int size){
  
  int s1 = 0, s2 = 0, e1 = size-1, e2;
  
  while(s2 < e2){
    
      if(s1<=e1){
          
          if(arr[s1] != 2){
              s1++;
          }
          else if(arr[e1] == 2){
              e1--;
          }
          else{
              swap(arr[s1], arr[e1]);
          }
          e2 = e1;
      }
      else{
          
          if(arr[e2] == 1){
              e2--;
          }
          else if(arr[s2] == 0){
              s2++;
          }
          else{
              swap(arr[s2], arr[e2]);
          }
      }
  }
}

int main(){
    
    int arr[10] = {1,1,2,2,0,0,1,0,1,2};
    int size = 10;
    
    cout << "***Unsorted Array***" << endl;
    printArray(arr,size);
    
    sortArray(arr, size);
    
    cout << "***Sorted Array***" << endl;
    printArray(arr, size);
    
}

Hi @amanraiii thanks for your message and welcome to the community!

I changed your line 14 slightly and it worked:

int s1 = 0, s2 = 0, e1 = size-1, e2 = 1;

Note that e2 is now set to a value whereas previously it was just defined.

2 Likes

Thanks for your help Ian, I assigned e2 some value and it worked. But can you specifically tell me why this problem is only happening in replit and not on other platforms so I can make sure I do not repeat this mistake again.

1 Like

Hi @amanraiii sorry I just moderate here, I don’t have access to the code. From a teaching perspective I can comment though!

It makes sense to give a variable an initial value because otherwise e2 could be pointing to any value held in memory that is yet to be disposed of by the OS garbage collection.

1 Like

I don’t know why warnings are disabled by default. Click on the three dots in the top right > show hidden files, and replace -Wno-everything with -Wmost -Werror in Makefile to prevent these mistakes.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.