Why is My C Code Unexpectedly Changing Other Elements in a 2D Array?

  • Thread starter Thread starter kyacout
  • Start date Start date
  • Tags Tags
    Array Change
Click For Summary
SUMMARY

The forum discussion centers on a C code snippet that modifies a 2D array, specifically the variable gameBoardState. The unexpected behavior occurs when changes to gameBoardState[i][col] inadvertently affect other elements, such as gameBoardState[4][6]. Participants emphasize the importance of verifying data types for gameBoardState, playerTurn, i, and col, and suggest using a debugger to trace the source of the issue.

PREREQUISITES
  • Understanding of C programming language syntax and semantics
  • Familiarity with 2D arrays in C
  • Knowledge of variable data types in C
  • Experience using debugging tools in C development environments
NEXT STEPS
  • Investigate C data types and their implications on memory management
  • Learn how to use a debugger effectively in C to trace variable changes
  • Explore common pitfalls in array manipulation in C programming
  • Study best practices for managing state in game development using C
USEFUL FOR

C developers, game programmers, and anyone troubleshooting unexpected behavior in array manipulation within their code.

kyacout
Messages
1
Reaction score
0
Code:
if(gameBoardState[i][col] == 0)
        {
            gameBoardState[i][col] = playerTurn;
            break;
        }

This code is supposed to change the values in gameBoardState[col] (a 2D array), but it changes values in other elements too. For example, when col = 0, and i = 5, gameBoardState[4][6] is changed with the same value as well.
 
Technology news on Phys.org
kyacout said:
Code:
if(gameBoardState[i][col] == 0)
        {
            gameBoardState[i][col] = playerTurn;
            break;
        }

This code is supposed to change the values in gameBoardState[col] (a 2D array), but it changes values in other elements too. For example, when col = 0, and i = 5, gameBoardState[4][6] is changed with the same value as well.


How are you sure it's getting changed by this piece of code & not elsewhere?
Did you check this in the debugger?

Also what's the datatype of gameboardState, playerTurn, i & col?
 

Similar threads

  • · Replies 22 ·
Replies
22
Views
5K
  • · Replies 17 ·
Replies
17
Views
4K
  • · Replies 33 ·
2
Replies
33
Views
7K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
Replies
2
Views
2K
  • · Replies 4 ·
Replies
4
Views
3K
Replies
3
Views
3K
  • · Replies 31 ·
2
Replies
31
Views
3K
Replies
235
Views
15K