Lewcuh Lewcuh - 10 months ago 52
C Question

Nested Loop Unexpected Behavior

I'm trying to debug my program with a nested loop to print out all the values in a 2d array. I was getting some unexpected behavior from the loop so i commented out some things and added a simple printf.

`int u = 0;
int y = 0;
char m = 'm';
for (u; u < 12; u++)
for (y; y < 5; y++)
//transition[u][x] = &m;
printf("o"); //this nested loop isnt working????
//printf("%c", *transition[u][y]);

Clearly this should print 12 rows of 5 'o's. But instead it is only printing out one row of 5 'o's followed by 11 newlines.

Edit: Thanks a lot! Silly mistake, I failed to realize that y would not set itself back to 0 on the second run through the loop. I guess overlooked this because I'm too used to Java initializing and setting the increment variable within the loop statement.


Your for initial statement doesn't mean anything:

for (y; y < 12; y++) 

The first statement is just y. Which has no side effects so you are not actually resetting y to 0 after first innermost loop. So from next iteration of outer loop, y == 5 and the inner loop is not executed at all.

You should do

for (y = 0; y < 12; y++)