简体   繁体   中英

C: odd behaviour with nested loop and array

I have an array of int that is terminated with a '\0' created elsewhere in my code. I know it's null terminated because I've tested it.

Say, for this example, the array is [7, 8, 9, 11, 12, '\0']

When I feed it to my function:

int edgesInCluster(Graph *g, int *nodes) {
    int count = 0;
    int i = 0;
    int j = 0;
    while(nodes[i] != '\0') {
        while(nodes[j] != '\0') {
            if(i<j) {
                printf("%i %i\n", nodes[i], nodes[j]);
                count += isNeighbour(g, nodes[i], nodes[j]);
            }
            j++;
        }
        i++;
    }
    return count;
}

The printf is outputting:

7 7
7 8
7 9
7 11
7 12

When it should be outputting:

7 8
7 9
7 11
7 12
8 9
8 11
8 12
9 11
9 12
11 12

Which means that for some reason either 'i' isn't being incremented (but we can see that it is) or nodes[0] == '\0' which we know isn't true since the loop with 'j' works fine.

So, any ideas what's going on?

PS when I change the whiles to for loops, it works but only if I know the length of 'nodes'

You don't reset your j after the inner loop.

But why such a horribly verbose code? Try this:

size_t count = 0;

for (size_t i = 0; nodes[i]; ++i)
{
  for (size_t j = i + 1;  nodes[j]; ++j)
  {
    printf("%i %i\n", nodes[i], nodes[j]);
    count += isNeighbour(g, nodes[i], nodes[j]);
  }
}

return count;

(If you want strict ANSI C89, you have to pull the declarations of i and j out of the loops of course.)

Also note that '\0' is a char -literal of value 0, so you might just as well, and more correctly, say 0 . And instead of if (x != 0) you can just say if (x) , which is what I did in the for loops.

You aren't resetting the value for j at the beginning of the j loop. That way, after the first loop, nodes[j] is '\0' for all following loops, aborting the j loop immediately.

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