C 被覆盖的矩阵中数组的前两个索引
我有一个矩阵的结构,定义如下:C 被覆盖的矩阵中数组的前两个索引,c,C,我有一个矩阵的结构,定义如下: struct tunnelmap { size_t height; size_t width; int** matrix; }; typedef struct tunnelmap TunnelMap; TunnelMap* createTunnelMap(size_t height, size_t width) { TunnelMap* pTunnelMap = malloc(sizeof(TunnelMap)); pTu
struct tunnelmap {
size_t height;
size_t width;
int** matrix;
};
typedef struct tunnelmap TunnelMap;
TunnelMap* createTunnelMap(size_t height, size_t width) {
TunnelMap* pTunnelMap = malloc(sizeof(TunnelMap));
pTunnelMap->height = height;
pTunnelMap->width = width;
pTunnelMap->matrix = malloc(height * sizeof(int));
for (size_t row = 0; row < height; row++) {
pTunnelMap->matrix[row] = malloc(width * sizeof(int));
for (size_t column = 0; column < width; column++) {
pTunnelMap->matrix[row][column] = 1;
}
}
return pTunnelMap;
}
以及如下所示的初始化功能:
struct tunnelmap {
size_t height;
size_t width;
int** matrix;
};
typedef struct tunnelmap TunnelMap;
TunnelMap* createTunnelMap(size_t height, size_t width) {
TunnelMap* pTunnelMap = malloc(sizeof(TunnelMap));
pTunnelMap->height = height;
pTunnelMap->width = width;
pTunnelMap->matrix = malloc(height * sizeof(int));
for (size_t row = 0; row < height; row++) {
pTunnelMap->matrix[row] = malloc(width * sizeof(int));
for (size_t column = 0; column < width; column++) {
pTunnelMap->matrix[row][column] = 1;
}
}
return pTunnelMap;
}
矩阵第一“行”的前两个元素似乎是乱码数据,而矩阵的其余部分似乎是有序的:
printf("%d\n", tm->matrix[0][0]); // --> -1016700064
printf("%d\n", tm->matrix[0][1]); // --> 22063
printf("%d\n", tm->matrix[0][2]); // --> 1
printf("%d\n", tm->matrix[0][3]); // --> 1
printf("%d\n", tm->matrix[1][0]); // --> 1
printf("%d\n", tm->matrix[2][5]); // --> 1
printf("%d\n", tm->matrix[3][2]); // --> 1
printf("%d\n", tm->matrix[4][6]); // --> 1
我已经对矩阵中的项目进行了适当的迭代,以确保实际情况是这样的,而且确实如此。每次运行程序后,[0][0]
单元格和[0][1]
单元格都是看似随机的整数,而所有其他单元格都正确初始化为1
有人知道我做错了什么吗?我最初的想法是,
tunnelmap
结构上的height
和width
属性以某种方式导致了这个问题,但我不知道如何证明这一点。这里:pTunnelMap->matrix=malloc(height*sizeof(int))
,您要使用sizeof(int*)
,因为数组的每个元素都有一个指向int的指针。@MOehm-Ah!是的,谢谢!如果你想把它作为一个答案,我会非常乐意把它标记为一个被接受的答案。永远不要忘记,内存是可以线性寻址的,而矩阵访问是二维的。因此,当你访问矩阵[i][j]
时,你实际上是在访问矩阵[i*width+j]
@fvdalcin:那不是真的。如果您将数组定义为int-matrix[M][N]
,这是正确的,但当您创建具有动态分配的矩阵时,情况就不是这样了:matrix
是指针数组,每个指针都持有整数数组的句柄。这里:pTunnelMap->matrix=malloc(height*sizeof(int))
,您要使用sizeof(int*)
,因为数组的每个元素都有一个指向int的指针。@MOehm-Ah!是的,谢谢!如果你想把它作为一个答案,我会非常乐意把它标记为一个被接受的答案。永远不要忘记,内存是可以线性寻址的,而矩阵访问是二维的。因此,当你访问矩阵[i][j]
时,你实际上是在访问矩阵[i*width+j]
@fvdalcin:那不是真的。如果您将数组定义为int-matrix[M][N]
,这是正确的,但当您创建具有动态分配的矩阵时(如此处所述):matrix
是指针数组,每个指针都持有整数数组的句柄。