[英]Two-dimensional dynamic array pointer access
p = (int *)malloc(m * n * sizeof(int));
如果我使用p
作为二维动态数组,如何访问里面的元素?
If you can rely on your C implementation to support variable-length arrays (an optional feature), then a pretty good way would be to declare p
as a pointer to (variable-length) array instead of a pointer to int
:如果您可以依靠您的 C 实现来支持可变长度数组(一个可选功能),那么一个很好的方法是将
p
声明为指向(可变长度)数组的指针,而不是指向int
的指针:
int (*p)[n] = malloc(m * sizeof(*p)); // m rows, n columns
Then you access elements using ordinary double indexes, just as if you had declared an ordinary 2D array:然后使用普通的双索引访问元素,就像声明一个普通的 2D 数组一样:
p[0][0] = 1;
p[m-1][n-1] = 42;
int q = p[2][1];
Most widely used C implementations do support VLAs, but Microsoft's is a notable exception.最广泛使用的 C 实现确实支持 VLA,但 Microsoft 是一个明显的例外。
I'd personally prefer using wohlstad's method, but you could also variably-modified types, which are an optional feature of C11, but will probably be mandated in C2x :我个人更喜欢使用 wohlstad 的方法,但您也可以可变地修改类型,这是 C11 的可选功能,但可能会在 C2x 中强制执行:
int (*p)[m] = malloc(n * sizeof *p);
This can now be used just like a normal 2d array with automatic storage duration.现在可以像使用具有自动存储持续时间的普通二维数组一样使用它。
int n = 12, m = 9;
int (*p)[m] = malloc(n * sizeof *p);
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
p[i][j] = i * m + j;
printf("%d\n", p[4][2]);
free(p);
I'll assume m is the number of columns, and n the number of rows (you can use n instead of m in my answer if it's the opposite).我假设m是列数,而n是行数(如果相反,您可以在我的答案中使用 n 而不是 m )。
In order to access the 2D array, you need 2 indices - let's call them x
and y
:为了访问 2D 数组,您需要 2 个索引 - 我们称它们为
x
和y
:
x
index will be in the range 0 .. m-1 , and x
索引将在0 .. m-1范围内,并且y
index will be in the range 0 .. n-1 y
索引将在0 .. n-1范围内
You can calculate the index for your p
array in the following way:您可以通过以下方式计算
p
数组的索引:
int p_idx = y * m + x
Then you can access your arrays element eg this way:然后您可以通过以下方式访问您的数组元素:
p[p_idx] = 111; // set an element value
int a = p[p_idx]; // get an element value
You can't use p
as a two-dimensional array.您不能将
p
用作二维数组。 It's a single integer pointer.它是一个整数指针。 Two-dimensional (dynamically allocated) implies nested pointers.
二维(动态分配)意味着嵌套指针。 However, you can represent a two-dimensional array in a "flattened" form.
但是,您可以以“扁平化”形式表示二维数组。 Here's some code that might offer a helpful explanation:
下面是一些可能提供有用解释的代码:
#include <stdio.h>
#include <stdlib.h>
int main(){
// Populating a 10x5 matrix
int m = 10;
int n = 5;
int* p = (int*) malloc(m*n*sizeof(int));
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
// Each row has n elements; to get the
// "flattened" index, treating the MxN
// matrix as row-major ordered (reading
// left-to-right, and THEN down the rows):
int flattened_index = (i * n) + j;
// E.g., populate with multiplication table data
p[flattened_index] = (i + 1) * (j + 1);
printf("%d\t", p[flattened_index]);
}
printf("\n");
}
// Inversely, to convert a flattened index to a
// row and column, you have to use modulus
// arithmetic
int flattened_index = 21;
int row = flattened_index / n; // Rounded-down integer division
int column = flattened_index % n; // Remainder after division
printf("%d * %d = %d\n", row + 1, column + 1, p[flattened_index]);
return 0;
}
This outputs:这输出:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
6 12 18 24 30
7 14 21 28 35
8 16 24 32 40
9 18 27 36 45
10 20 30 40 50
5 * 2 = 10
You are actually creating a single-dimensional array.您实际上是在创建一个一维数组。 But still, we can use it to hold a matrix considering the fact in C a multidimensional array, eg int mat[m][n], is stored in contiguous memory itself.
但是,考虑到在 C 中一个多维数组,例如 int mat[m][n],我们可以使用它来保存一个矩阵,它本身存储在连续的内存中。
#include <iostream>
int main()
{
int m, n;
std::cin >> m >> n;
int* mat_ptr = (int*)malloc(m * n * sizeof(int));
if (mat_ptr)
{
for (int row = 0; row < m; ++row)
{
for (int col = 0; col < n; ++col)
{
*(mat_ptr + ((row * n) + col)) = (row * n) + col;
}
}
for (int row = 0; row < m; ++row)
{
for (int col = 0; col < n; ++col)
{
std::cout << *(mat_ptr + ((row * n) + col)) << " ";
}
std::cout << std::endl;
}
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.