首页 > 解决方案 > 如何在一个位置将数组元素向右移动?C语言

问题描述

我必须编写函数(array_rshift)以仅使用数组开头和结尾的指针将数组的每个元素右移 1 个位置。我有向左移动元素的代码,但我真的不明白如何在右侧移动。

这里有一些代码:


#include "pch.h"
#include <stdio.h>

int arr[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int *begin = arr;
int *end = arr + 10;
int copy[10] = { 0, };

#define PRINT(a) \
for (size_t i = 0; i < size; i++)\
    if (i != size - 1)\
        printf("%2i, ", *(a + i));\
    else\
        printf("%2i]\n", *(a + i))\

// Swap the contents of two variables.
void swap(int* a, int* b)
{
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

// Return the sum of the array from 'begin' to 'end'.
int array_sum(int *begin, int *end)
{
    int size = end - begin;
    int p = 0;
    int result = 0;
    while (size)
    {

        result += *(begin + p);
        p++;
        size -= 1;
    }
    return result;

}

// Reverse the array from 'begin' to 'end'.
void array_reverse(int *begin, int *end)
{

    end--;
    while (begin < end)
    {

        swap(begin, end);

        begin++;
        end--;

    }
}

// Copy the array from 'begin' to 'end' into 'dst'.
// The dst array must be large enough.
// The two arrays do not overlap.
void array_copy(int *dst, int *begin, int *end)
{
    while (begin < end)
    {
        *dst = *begin;
        begin++;
        dst++;
    }

}

// Shift the array from 'begin' to 'end' by one position to the right.
// The leftmost value will not change.
// The rightmost value will be lost.
// For instance:
// - Before: 1 2 3 4 5
// - After:  1 1 2 3 4
void array_rshift(int *begin, int *end)
{   
    int size = end - begin;
    for (int i = 0; i < size -1; i++)
    {
        *(begin + i) = *(begin + i + 1);
    }
}

int main()

{
    size_t size = end - begin;

    printf("Initial arr  = [");
    PRINT(arr);

    int sum = array_sum(begin, end);
    printf("sum          = %2i\n", sum);

    array_reverse(begin, end);
    printf("Reversed arr = [");
    PRINT(arr);

    array_copy(copy, begin, end);
    printf("Copy         = [");
    PRINT(copy);

    array_rshift(begin, end);
    array_rshift(begin, end);
    array_rshift(begin, end);
    printf("Shifted arr  = [");
    PRINT(arr);
}

预期结果如下:

Shifted arr  = [ 10, 10, 10, 10, 9, 8, 7, 6, 5, 4]

但我有这个:

Shifted arr  = [ 7, 6, 5, 4, 3, 2, 1, 1, 1, 1]

有人知道怎么做吗?

标签: carrays

解决方案


推荐阅读