如何获得在C / C ++多维数组的列? [英] How to get column of a multidimensional array in C/C++?
问题描述
int matrix[9][9],*p;
p=matrix[0];
这个工程,并给出矩阵
,第一行,但如何让矩阵的第一列
我试着 p =矩阵[] [0];
?此外,我不明白为什么低于code编译器得到错误?
this works and gives first row of matrix
, but how to get first column of matrix
I've tried p=matrix[][0];
? Also I don't understand why below code gets compiler error ?
int matrix[9][9],p[9]; // it looks really ugly, byt why it doesn't work ?
p=matrix[0]; // compiler gives "invalid array assigment"
是不是因为多维数组的数组的数组 - 我们应该相互preT 矩阵[i] [j]的
为第j个元素的第i个嵌套数组?
is it because multidimensional arrays are arrays of arrays - and we should interpret matrix[i][j]
as j-th element of i-th nested array ?
推荐答案
在C / C ++,多维数组实际上存储为一维数组(在内存中)。您的2D矩阵被存储为具有行第一排序的一维数组。这就是为什么得到一个列出它是不容易的,而不是由默认提供的。 有一个在内存中没有连续的数组,你可以得到一个指针,从而重新presents多维数组的一列见下图:
In C/C++, multidimensional arrays are actually stored as one dimensional arrays (in the memory). Your 2D matrix is stored as a one dimensional array with row-first ordering. That is why getting a column out of it is not easy, and not provided by default. There is no contiguous array in the memory that you can get a pointer to which represents a column of a multidimensional array. See below:
当你做 P =矩阵[0]
,您是刚开始指针的第一个元素矩阵[0] [0]
,这使得你认为你有指针第一行。其实,这是一个指向包含矩阵整个连续数组
,如下:
When you do p=matrix[0]
, you are just getting the pointer to the first element matrix[0][0]
, and that makes you think that you got the pointer to first row. Actually, it is a pointer to the entire contiguous array that holds matrix
, as follows:
matrix[0][0]
matrix[0][1]
matrix[0][2]
.
.
matrix[1][0]
matrix[1][1]
matrix[1][2]
.
.
matrix[8][0]
matrix[8][1]
matrix[8][2]
.
.
matrix[8][8]
如上所示,任何给定列的元件由在相应的行的其他元素分离。
As seen above, the elements of any given column are separated by other elements in the corresponding rows.
所以,作为一个侧面说明,用指针 P
,您可以通过矩阵的整个81元素走路,如果你想。
So, as a side note, with pointer p
, you can walk through the entire 81 elements of your matrix if you wanted to.
这篇关于如何获得在C / C ++多维数组的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!