简体   繁体   English

为什么在循环中将j初始化为0而不是其递增值?

[英]Why j is initialized to 0 instead of its incremented value in the loop?

Consider the following c code: 考虑下面的C代码:

int main()
{
    int a[5] = {5, 2, 1, 6, 3}, b[5] = {1, 6, 3, 2, 5}, c[10], i = 0, j = 0, k = 0;
    for (i = 0 ; i < 5 ; i++)
    {
        while (a[i] != b[j])
            j++;
        c[k]   = a[i];
        c[k+1] = b[j];
        k      = k + 2;
    }
    for (i = 0 ; i < 10 ; i += 2)
        printf("%d->%d\n", c[i], c[i + 1]);
    getch();
}

The program prints two same numbers each choosen from a[5] and b[5] 该程序打印两个相同的数字,每个数字都从a [5]和b [5]中选择

Q: j is initialized only once and in the loop the value of j gets incremented, so it may get incremented beyond 5 as no again initialization of j takes place inside the loop, hence the o/p should be some garbage value, but it is not? 问:j仅被初始化一次,并且在循环中j的值被递增,因此它可能被递增至5以上,因为在循环内不再发生j的初始化,因此o / p应该是一些垃圾值,但是不是? Why? 为什么?

j contains 0 when entering the first for loop. 进入第一个for循环时, j包含0。 It becomes 4 when exiting the while loop as only then will the condition a[i] != b[j] be false. 退出while循环时它变为4,因为只有这样条件a[i] != b[j]为假。

Then, in the next iteration of the first for loop, j gets incremented and you try to read past the array ( b[5] , b[6] etc) and this invokes Undefined Behavior which means that anything can happen. 然后,在第一个for循环的下一次迭代中, j递增,并且您尝试读取数组( b[5]b[6]等),这将调用未定义行为 ,这意味着任何事情都可能发生。

The reason that it worked perfectly is by pure luck. 它运行良好的原因纯粹是靠运气。 But you cannot rely on this. 但是您不能依靠它。

If you print the address of the array elements whose values match, you can see the truth of @Marian's comment, that j indexes the same array as i does, after the first match. 如果打印数组元素,其匹配的地址 ,你可以看到@玛丽安的评论的道理,那j指标为同一阵列i呢,后的首场比赛。

#include <stdio.h>

int main()
{
    int a[5] = {5, 2, 1, 6, 3}, b[5] = {1, 6, 3, 2, 5}, c[10], i = 0, j = 0, k = 0;
    for (i = 0 ; i < 5 ; i++)
    {
        while (a[i] != b[j])
            j++;
        printf ("%p %p\n", (void*)&a[i], (void*)&b[j]);   // added a cue
        c[k]   = a[i];
        c[k+1] = b[j];
        k      = k + 2;
    }
    for (i = 0 ; i < 10 ; i += 2)
        printf("%d->%d\n", c[i], c[i + 1]);
    getch();
}

Program output 程序输出

0018FF2C 0018FF24
0018FF30 0018FF30
0018FF34 0018FF34
0018FF38 0018FF38
0018FF3C 0018FF3C
5->5
2->2
1->1
6->6
3->3

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

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