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
AI Thread Summary
The discussion centers on a code snippet intended to update a specific element in a 2D array, gameBoardState, based on the player's turn. The issue arises when changes to gameBoardState[i][col] unexpectedly affect other elements, such as gameBoardState[4][6]. Participants question whether the problem lies within the provided code or if it stems from other parts of the program. They emphasize the importance of using a debugger to trace changes and suggest verifying the data types of gameBoardState, playerTurn, i, and col to ensure proper functionality. The conversation highlights the need for careful debugging and understanding of data types in programming to avoid unintended side effects.
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?
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I have a quick questions. I am going through a book on C programming on my own. Afterwards, I plan to go through something call data structures and algorithms on my own also in C. I also need to learn C++, Matlab and for personal interest Haskell. For the two topic of data structures and algorithms, I understand there are standard ones across all programming languages. After learning it through C, what would be the biggest issue when trying to implement the same data...
Back
Top