繁体   English   中英

使用指针向右移动数组元素

[英]Shift array elements to the right using pointers

我无法弄清楚如何使用指针(而不是使用交换)将数组的元素向右移动。 我试图弄清楚指针从哪里开始以及它是如何递增的,但是当我仅通过打印数组值来测试它时,它总是会弄乱数组的 output。 请帮助我很沮丧。

// 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;
}

您的代码有几个问题。

  • 首先,它包含一个无限循环: ptr < arr + n - 1对于大小大于 1 的 arrays 为真。这在整个循环中是不变的 仅更改arr的内容。
  • 其次,它有一个潜在的越界,访问arr[*ptr] ,因为*ptr是存储在数组中的任意 integer 。

有一个标准算法可以执行此操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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