我不确定如何跟踪代码数组?

时间:2019-02-19 04:05:27

标签: c arrays loops trace

我不了解如何跟踪数组。我觉得我知道,但后来又把它弄乱了。我知道如何交换值,但是我仍然感到困惑。除了代码外,我还以注释的形式写问题。有人可以帮我追踪一下那部分吗?

#include <stdio.h>

int main()
{
    int a[5]={1,2,3,4,5};
    int i,j,temp;

    for (j=1; j<5; j++) 
        for (i=0; i<5-j; i=i+2) 
        {
            printf("%d %d\n",i,i+j); //I got this part right
            temp = a[i]; //from here I get confused
            a[i] = a[i+j]; //how is the addition inside working??
            a[i+j] = temp; //temp = the index's value
        }
            for (i=0; i<5; i++)
            printf("a[%d] = %d\n",i,a[i]);//what is i supposed to be here??
}

Output:
0 1
2 3
0 2
2 4
0 3
0 4
a[0] = 2 //from here on I get lost
a[1] = 1
a[2] = 5
a[3] = 4
a[4] = 3

3 个答案:

答案 0 :(得分:0)

为什么不在每个循环中打印整个数组,那样您就可以看到值的移动方式,例如在交换0,1元素的步骤中,所以数组为{2,1、3、4、5 },然后是2,3,所以{2,1,4,3,5},然后是0.2,所以{4,1,2,3,5},2,4,=> {4,1,5,3 ,2},0,3 {3,1,5,4,2},0 4 {2,1,5,4,3}

答案 1 :(得分:0)

我猜您对C编程了解不多。因此,这里有一些关于数组的内容:

  1. 一个数组(此处为int a[5]={1,2,3,4,5})是连续分配的内存块。
  2. 数组a [n]的大小为'n'(存储n个数组类型的值,在这里int),索引从0到n-1。表示从a[0]a[n-1]访问n个值。
  3. 有多维数组(请阅读!)。

此处给出的逻辑:

temp = a[i];   //temp gets a[i]'s value and not the value of i
a[i] = a[i+j];
a[i+j] = temp;

这是使用临时变量temp的标准swap(a,b)操作。只是这里的“ a”和“ b”是数组的元素。

循环的设计方式是在每次迭代中访问数组的不同元素。这会改变数组的位置。

很明显:

printf("a[%d] = %d\n",i,a[i]); // i here is the index used to access a's ith element

答案 2 :(得分:0)

我发现我做错了。我只是试图做数学运算并更改该位置的值。我必须打开空间并移出旧数字以放入新数字。然后旧数字将移至剩余的空白空间。它实际上只是交换,但有助于更好地查看它。

因此,在{1,2,3,4,5}中,如果我尝试将a [3] = 4放入a [1] = 2,则值4将进入a [1]。
拥有2的a [1]将必须离开,拥有4的a [3]将进入。
退出的2将进入a [3] = 2中之前4的位置。

所以现在a [1] = 4和a [3] = 2。 因此,交换数组现在看起来像{1,4,3,2,5}