获取动态二维数组元素的行/列
我目前正在使用以下代码来获取 2D int 数组中元素的当前行和列:
const int num_rows = 5;
const int num_columns = 7;
int a[num_rows][num_columns];
int *p = &a[2][4];
int row = (p - &a[0][0]) / num_columns;
int col = (p - &a[row][0]);
这工作正常,但现在我需要更改代码以将行数和列数作为参数。据我所知,这意味着我需要动态创建 2D 数组:
int** ary = new int*[sizeX];
for(int i = 0; i < sizeX; ++i)
ary[i] = new int[sizeY];
如果我以这种方式创建 2D 数组,上面查找行/列的代码就会中断。我能做些什么?
I am currently using the following code to get the current row and column of an element in a 2D int array:
const int num_rows = 5;
const int num_columns = 7;
int a[num_rows][num_columns];
int *p = &a[2][4];
int row = (p - &a[0][0]) / num_columns;
int col = (p - &a[row][0]);
This works fine but now I need to change the code to take the number of rows and columns as a parameter. As far as I know, this means I need to create the 2D array dynamically:
int** ary = new int*[sizeX];
for(int i = 0; i < sizeX; ++i)
ary[i] = new int[sizeY];
If I create the 2D array this way, the above code to find the row/column breaks. What can I do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
远离指针算术是一个非常好的主意。不要这样做!您本质上是减去指针并将该数字除以 num_columns,该数字将是随机的。
如果要获取某个元素的行/列,请一次搜索数组中的一个元素。
It's a very good idea to stay way from pointer arithmetic. Don't do this! You are essentially subtracting the pointer and divide that number by num_columns, and that number will be random.
If you want to get the row/column of an element, search the array one element at a time.