简体   繁体   中英

C++ 2d array index error

I have a question regarding 2d array index. Here player_board is declared as a double pointer to char, which is a 2d array. Then I allocate the memory and everything seems to work just fine. x_vals and y_vals are two vectors that store x coordinates and y coordinates. I am trying to replace the original value of given x, y value with 'A'. When I print out the element of x_vals and y_vals it seems fine but when I use them as index, they begin to begin randomly assign. Here is my code...How should I solve this? Thx for helping

for(unsigned int i = 0; i < x_vals.size(); i++) {
    cout << x_vals.at(i) - 48 << y_vals.at(i) - 48 << endl;
    player_board[x_vals.at(i) - 48][y_vals.at(i) - 48] = 'A';
}

I'm assuming x_vals and y_vals are declared as vector of int or uint, thus when trying to obtain a cell at a certain index in a 2d dimentional matrix you might provide the matrix with negative values. For example lets say your x_val.at(1) = 10 -> then you will try to access the cell at index -38. Correct me if I'm wrong and kindly provide some more information about the types of x_vals and y_vals and the matrix allocation of player_board.

When you print out values of x_vals.at(i) - 48 and y_vals.at(i) - 48, are you not getting some negative values? I think you are getting these negative values and then trying to access a value in an array at a negative index eg player_board[-10]...

Maybe you could try using the absolute values of x_vals.at(i) - 48 and y_vals.at(i) - 48 as you index values

Also are you sure when you use the index values they do not go outside the declared range of your array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM