c - 逆时针旋转数组,一步中出现意外的调试输出

标签 c arrays debugging data-structures

我使用最简单的方法逆时针旋转数组,即通过在临时数组中存储从索引 = 0 到索引 = 所需旋转位置数的元素,最后将这些元素插入另一个数组的末尾。代码如下:

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int *a, *temp, i, j=0, n,np,*b;
    printf("Enter no. of elements in arr:\n");
    scanf("%d",&n);
    a=(int*) malloc(n*sizeof(int));//Primary array
    b=(int*) malloc(n*sizeof(int));//Final array that would be printed in the end
    printf("Enter elements:\n");
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);
    printf("Enter positions to be rotated anti-clockwise:\n");
    scanf("%d",&np);
    temp=(int*) malloc(np*sizeof(int));//storing elements left of index=0
    for(i=0;i<np;i++,j++)
    {
        //printf("hi\n");
        temp[j]=a[i];
        printf("temp[%d]=%d\n",j,temp[j]);
    }
    j=0;
    printf("After rotating:\n");
    for(i=n-1;i>=0;i--)
    {
        printf("i=%d ",i);
        b[i-np]=a[i];
        printf("b[%d]=%d\n",i-np,b[i]); /*Here is 1 unexpected thing happening, the program is not picking up correct value of array a at index i.*/
    }
    for(i=np-1;i<n;i++,j++)
        b[i]=temp[j];//storing temp elements in final array

    printf("Finally matrix is\n");

    for(i=0;i<n;i++)
        printf("%d\n",b[i]);

    getch();
    return 0;
}

最佳答案

无论您尝试向一个方向还是向另一个方向旋转数组元素,过程始终是相同的:获取要移动到另一个极端的极值元素的副本。然后,将下一个元素(从您保存到另一侧的元素)复制到您打开的孔中。最后,用保存的元素盖住洞。

typedef int ARRAY_ELEMENT;
ARRAY_ELEMENT the_array[N_ELEMENTS];

/* to put the first element at the end */
ARRAY_ELEMENT saved_element = the_array[0];
for (int i = 1; i < N_ELEMENTS; i++) the_array[i-1] = the_array[i];
the_array[N_ELEMENTS-1] = saved_element;

/* to put the last element at the beginning */
ARRAY_ELEMENT saved_element = the_array[N_ELEMENTS-1];
for (int i = N_ELEMENTS-1; i > 0; i--) the_array[i] = the_array[i-1];
the_array[0] = saved_element;

您也可以通过交换第一个元素与第二个元素、第二个元素与第三个元素等......直到倒数第二个元素和最后一个元素来实现此目的。您将达到相同的结果,但作业数量更多(每轮三个作业,而不是一个)

如果您只想旋转数组的一部分,请设计一个例程,将指向第一个元素的指针和这些元素的数量视为参数......然后将其应用于您要旋转的数组部分。

void rotate_upwards(ARRAY_ELEMENT *a, size_t n) /* a[0] -> a[1], a[1] -> a[2] ... */
{
    ARRAY_ELEMENT saved = a[n-1];
    int i;
    for (i = n-1; i > 0; i--) a[i] = a[i-1];
    a[i] = saved;
} /* rotate_upwards */

void rotate_downwards(ARRAY_ELEMENT *a, size_t n) /* a[0] <- a[1], ... */
{
    ARRAY_ELEMENT saved = a[0];
    int i;
    for (i = 0; i < n-1; i++) a[i] = a[i+1];
    a[i] = saved;
} /* rotate_downwards */

如果您想在 33 位置旋转 array[100]5 个元素,您可以使用

rotate_downwards(array + 33, 5);

并且您将仅旋转数组的一部分。

关于c - 逆时针旋转数组,一步中出现意外的调试输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31091518/

相关文章:

arrays - 遍历数组并在找到某个值时启动一个新数组

django - 使用 Netbeans 调试 Django 时 ipython 显示乱码

python - ValueError : not enough values to unpack (expected 2, got 1) when splitting line

c - 二维字符数组,像表格一样扫描和打印

C++:为什么 int array[size] 有效?

c - 当 Ruby 中的 system() 调用时,GCC 无法编译

java - 为什么我可以给一个太大的int赋值?Java如何处理它?

ruby 调试器直接进入一个 block ?

C、gcc编译简单程序出错

c - 如何在编译的 C 代码中隐藏文本?