简体   繁体   中英

Shift array elements to the right using pointers

I am having trouble figuring out how to shift the elements of an array to the right using pointers (and not using swap). I have tried to play around with where the pointer starts and how it increments but it always messes up the output of the array when I test it just by printing the array values. Please help I am so frustrated.

// REQUIRES: there are at least n elements in arr;
//           n >= 1
// MODIFIES: the elements in arr
// EFFECTS:  All elements are "shifted" right by one unit, with the
//           last element wrapping around to the beginning.
// EXAMPLE:  If arr contains [0,1,3,3,4], it would be modified to
//           contain [4,0,1,3,3]
// NOTE:     You must use traversal by pointer.
//           You may not use an extra array.
void slideRight(int arr[], int n) {
    int *temp = arr;
    
    for(int *ptr = arr+1; ptr < arr + n - 1;) {
        arr[*ptr] = arr[*ptr-1];
    }
    arr[0] = *temp;
}

Your code has several problems.

  • First, it contains an infinite loop: ptr < arr + n - 1 is true for arrays of size larger than 1. This is unchanged throughout the loop . Only the contents of arr is changed.
  • Second, it has a potential out-of-bounds, accessing arr[*ptr] , since *ptr is some arbitrary integer stored in the array.

There is a standard algorithm that does exactly this operation:

void slideRight(int arr[], int n) {
  std::rotate(arr, arr + n - 1, arr + n);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM