用C索引多维数组 [英] Indexing multidimensional arrays in C
问题描述
我熟悉的多维数组这样被访问:改编[行] [COLS] 这是有道理的我,当我把它想象成一个网格或坐标系和定位点。但我困惑的线下。我明白这是一个指针捡一些结构位于结构的阵列中的我只是有一个很难想象哪个位置,这可能在坐标系中,我使用的术语重新present为...它的方式和东西位图是一个像素。
//这是什么线意味着什么* O =原行+ * + COLS山坳;为(行= 0;&行LT;排;排++)
对于(COL = 0;&山坳下,COLS;西++){
SOMETHING * O =原行+ * + COLS山坳;
SOMETHING * N =(*新)+行* COLS +(COLS-1-COL);
* N = * O;
}
想想阵列是如何在内存布局。多维数组只是数组的数组,所以说你有喜欢的东西数组[10] [10]。
内存布局将是:
[0] [0],[0] [1],.. [0] [9],[1] [0],[1] [1]。[9] [9]
这实际上是完全一样的分配的sizeof(某事)* 100
。
什么行 SOMETHING * O =原+行* COLS + COL;
被说是做一个指针类型的东西对象的指针地址应该是:原来的内存地址,添加行时间COLS它,将其放置在一行的开始,那么具体列添加到它获得到阵列中的一个对象的确切位置。
I'm familiar with multidimensional arrays being accessed as such: arr[rows][cols] which makes sense to me when I imagine it as a grid or coordinate system and locating points. But I'm confused about the line below. I understand it is picking up a pointer to some struct located in the array of structures I just have a hard time imagining which location this could represent in terms of the coordinate system I'm used to...its a bitmap by the way and SOMETHING is a pixel.
//what does this line mean SOMETHING *o = original + row*cols + col;
for (row=0; row < rows; row++)
for (col=0; col < cols; col++) {
SOMETHING* o = original + row*cols + col;
SOMETHING* n = (*new) + row*cols + (cols-1-col);
*n = *o;
}
Think about how arrays are laid out in memory. A multidimensional array is just an array of arrays, so say you had an array like SOMETHING[10][10].
The memory layout would be: [0][0], [0][1], .. [0][9], [1][0], [1][1].. [9][9]
This actually is exactly the same as allocating sizeof(SOMETHING)*100
.
What the line SOMETHING* o = original + row*cols + col;
is saying is "make a pointer to object of type SOMETHING. The pointer address should be: the memory address of original, add row times cols to it, which will place it at the start of a row, then add the specific column to it to get to the exact position of an object in the array."
这篇关于用C索引多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!