c - 如何在一个位置将数组元素向右移动?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]
有人知道怎么做吗?
解决方案
推荐阅读
- sql - SQL找不到变量?
- xslt - XSL-FO Region-Body 背景图片
- mail-server - 希望创建刻录机帐户
- python - 使用多个 csv 文件作为 CNN 的测试和训练集
- visual-studio - 是在不同的层中复制多个项目文件,还是在创建 Docker 映像时一次性复制更好?
- javascript - 如何在数字输入字段中添加逗号以获取多个重新编码
- swift - 从集合视图重新加载数据时的多个视图
- azure-sql-database - Azure SQL 高级数据安全 (ADS) 和安全中心定价
- leakcanary - 了解 LeakCanary 内存泄漏堆栈跟踪
- c++ - 如何使用new创建指向结构的指针数组?