[英]Pointer to multidimensional array
I'm trying to address matrix of struct, but some goes wrong. 我正在尝试处理结构矩阵,但是有些地方出错了。 This the code:
此代码:
typedef struct {
bool state;
float val;
char ch[11];
} st_t;
st_t matrix[3][5];
int main(int argc, char *argv[])
{
int i, j;
// Init matrix value matrix[i][j] = i.j
....
// Init matrix pointer
st_t (*pMatrix)[3][5];
pMatrix = &matrix;
// print address element
fprintf(stderr, "\n\nsizeof st_t:%d\n\n", sizeof(st_t) );
for( i = 0; i < 3; i++ )
{
for( j = 0; j < 5; j++ )
fprintf(stderr, "matrix[%d][%d] ADDR:%p pMatrix[%d][%d] ADDR:%p\n", i, j, &(matrix[i][j]), i, j, &pMatrix[i][j]);
fprintf(stderr, "\n");
}
return 0;
}
This is the output of code: 这是代码的输出:
sizeof st_t:16
matrix[0][0] ADDR:0x8049a00 pMatrix[0][0] ADDR:0x8049a00
matrix[0][1] ADDR:0x8049a10 pMatrix[0][1] ADDR:0x8049a50
matrix[0][2] ADDR:0x8049a20 pMatrix[0][2] ADDR:0x8049aa0
matrix[0][3] ADDR:0x8049a30 pMatrix[0][3] ADDR:0x8049af0
matrix[0][4] ADDR:0x8049a40 pMatrix[0][4] ADDR:0x8049b40
matrix[1][0] ADDR:0x8049a50 pMatrix[1][0] ADDR:0x8049af0
For example why does pMatrix[0][1] is different from address of matrix[0][1]? 例如,为什么pMatrix [0] [1]与矩阵[0] [1]的地址不同?
Thanks in advance. 提前致谢。
You have declared pMatrix
to be a pointer to a 3⨉5 matrix of st_t
, that is, it points to an array of 3 arrays of 5 st_t
objects. 您已将
pMatrix
声明为指向st_t的3×5矩阵的st_t
,也就是说,它指向5个st_t
对象的3个数组的数组。 Given this, pMatrix[0]
is an array of 3 arrays of 5 st_t
objects. 鉴于此,
pMatrix[0]
是一个由5个st_t
对象组成的3个数组的数组。 However, since it is an array, it is automatically converted to a pointer to the first element of the array. 但是,由于它是一个数组,它会自动转换为指向数组第一个元素的指针。 So it becomes a pointer to an array of 5
st_t
objects. 因此,它成为指向5个
st_t
对象的数组的指针。
Then pMatrix[0][0]
, pMatrix[0][1]
, pMatrix[0][2]
, and so on are successive arrays of 5 st_t
objects, not successive st_t
objects. 那么
pMatrix[0][0]
, pMatrix[0][1]
, pMatrix[0][2]
等是5个st_t
对象的连续数组,而不是连续的st_t
对象。
Most likely, what you want is: 您最可能想要的是:
// Declare pMatrix to be a pointer to an array of 5 st_t objects,
// and point it to the first row of matrix.
st_t (*pMatrix)[5] = matrix;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.