#Help with a loop.

1 messages · Page 1 of 1 (latest)

rare token
#

i have a loop to go through a linked list and pitch the nodes (players) in pairs (like players 1 and 2, 3 and 4, 5 and 6...) and the asks user to input the winner for each match.
here, temp is the amount of players there are, stage represents the stage they are in (can think of as wins), and playerNumber represents each players number as they are ID by their number. Currently, this code works for the first stage, where we go through each pair and ask for the winner, and the winners "int stage" attribute is incremented by one, however, when we have, lets say 8 players, we will end up with 4 rounds, where the final round displays the winner only, I cant get this code to loop for N amount of rounds where each time it is called upon, it only looks at the winners of last round.

cur = head; for (int i = 0; i < temp; i++) { while (cur != NULL) { printf("***************\n%dv%d\n", cur->playerNumber , cur->next->playerNumber); int winner; scanf("%d", &winner); if (winner == cur->playerNumber) { cur->stage++; } else { cur->next->stage++; } cur = cur->next->next; } }

patent starBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

tranquil tiger
#

Not enough code.

rare token
#

starting at line 115, ending at 131.

#

i was working on it today and wrote some other things such as a get_suitable_player function and lines 133-151. these are experimental so dont worry too much about them

tranquil tiger
#

The last player you add to the list will have its next pointer uninitialized. Dereferencing it is a guaranteed crash.

#

The last player having a garbage next pointer is easy to fix. Add this right after the first loop but before line 115 (cur = head):

if (cur)
        cur->next = NULL;```
#

After that you're still going to segfault inside the next loop because you dereference an unchecked pointer e.g. when you do cur = cur->next->next; on line 129.

#

You only null check cur itself at the beginning of each loop round, but you never check cur->next and basically reach one step too far into unsafe territory. It'll succeed only up until the second-last list node, but as you reach the last node, its next pointer will be either NULL or even worse uninitialized like in the version you linked to.

#

I'm not sure if there's actually a good reason for that sort of two-step pointer dereference in the loop, I don't know exactly what the idea is there. But seeing something like cur->next->next in a list iterator loop is a red flag based on a simple gut feeling.

#

Like I said I don't know what the intended behavior is exactly, but if it's on purpose then you at least need to null check those beforehand.