Vasu Vijayvargiya
Vasu Vijayvargiya

Reputation: 1

what if i swap an element with -1 index of array

  // ques-move all negative ele to one side
    
    #include<bits/stdc++.h>
    using namespace std;
    int main()
    {
        int n;
    cin >> n;
    
        int arr[n];
        for(int i=0;i<n;i++){
            cin >> arr[i];
        }
        int j=-1;
        int pivot = 0;
        for(int i=0;i<n;i++){
            if(arr[i]<pivot){
                swap(arr[i],arr[j])
                i++;
            }
        }
    return 0;
    }`
    

if we swap 1st index with -1 th index if it is negative then what will happen will a garbage value take place at arr[1]

Upvotes: 0

Views: 59

Answers (1)

Mark Ransom
Mark Ransom

Reputation: 308266

Accessing an array outside of its bounds of 0 to n-1 is undefined behavior. The most likely outcome is a garbage value, but literally anything could happen - your program could crash, you could erase your entire disk drive, or demons could fly from your nose.

Upvotes: 1

Related Questions