问题描述
我想用1D数组表示2D数组.函数将传递两个索引(x,y)和要存储的值.这两个标记将代表一维数组的单个元素,并进行相应的设置.我知道一维数组的大小必须为arrayWidth×arrayHeight,但是我不知道如何设置每个元素.
I want to represent a 2D array with a 1D array. A function will pass the two indicies (x,y) and the value to store. These two indicies would represent a single element of a 1D array, and set it accordingly. I know the 1D array needs to have the size of arrayWidth × arrayHeight, but I don't know how to set each element.
例如,如何区分(2,4,3)与(4,2,3)?我尝试将数组设置为x * y,但是2 * 4和4 * 2会在数组中产生相同的斑点,我需要它们有所不同.
For example, how do I distinguish (2,4,3) from (4,2,3)? I tried setting the array as the x*y, but 2*4 and 4*2 would result in the same spot in the array and I need them to be different.
推荐答案
您需要确定数组元素是以行顺序还是列顺序存储,然后保持一致. http://en.wikipedia.org/wiki/Row-major_order
You need to decide whether the array elements will be stored in row order or column order and then be consistent about it. http://en.wikipedia.org/wiki/Row-major_order
C语言对多维数组使用行顺序
The C language uses row order for Multidimensional arrays
要使用一维数组进行模拟,请将行索引乘以宽度,然后按以下方式添加列索引:
To simulate this with a single dimensional array, you multiply the row index by the width, and add the column index thus:
int array[width * height];
int SetElement(int row, int col, int value)
{
array[width * row + col] = value;
}
这篇关于将2D数组映射到1D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!