简体   繁体   English

C++ 二维数组索引错误

[英]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.这里 player_board 被声明为一个指向 char 的双指针,它是一个二维数组。 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. x_vals 和 y_vals 是存储 x 坐标和 y 坐标的两个向量。 I am trying to replace the original value of given x, y value with 'A'.我试图用'A'替换​​给定x,y值的原始值。 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.当我打印出 x_vals 和 y_vals 的元素时,它看起来不错,但是当我将它们用作索引时,它们开始随机分配。 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.我假设 x_vals 和 y_vals 被声明为 int 或 uint 的向量,因此当尝试获取二维维矩阵中某个索引处的单元格时,您可能会为矩阵提供负值。 For example lets say your x_val.at(1) = 10 -> then you will try to access the cell at index -38.例如,假设您的 x_val.at(1) = 10 -> 然后您将尝试访问索引 -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.如果我错了,请纠正我,并请提供有关 x_vals 和 y_vals 类型以及 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?当您打印出 x_vals.at(i) - 48 和 y_vals.at(i) - 48 的值时,您是否没有得到一些负值? 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]...我认为您正在获取这些负值,然后尝试以负索引访问数组中的值,例如 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也许您可以尝试使用 x_vals.at(i) - 48 和 y_vals.at(i) - 48 的绝对值作为索引值

Also are you sure when you use the index values they do not go outside the declared range of your array.您还确定当您使用索引值时,它们不会超出数组的声明范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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