Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: odd behaviour with nested loop and array

Tags:

arrays

c

loops

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?

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

like image 766
Griffin Avatar asked Mar 03 '26 21:03

Griffin


1 Answers

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.

like image 145
Kerrek SB Avatar answered Mar 06 '26 14:03

Kerrek SB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!