简体   繁体   中英

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

Consider the following c code:

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]

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? Why?

j contains 0 when entering the first for loop. It becomes 4 when exiting the while loop as only then will the condition a[i] != b[j] be false.

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.

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.

#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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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