gpt4 book ai didi

c - 指向 int 数组的指针数组

转载 作者:太空宇宙 更新时间:2023-11-04 01:12:38 26 4
gpt4 key购买 nike

经过一番折腾,我在 int A[2][3] 这样的声明中发现,A 是与 int(*)[3] 兼容的类型。我的理解是 A 可以用来指向前三个元素, A + 1 可以用来指向后三个。有什么方法可以声明指向数组的指针数组。

   ptr_array    

+----+ +----+----+----+
| | ----> | | | |
| | | 24 | 25 | 26 |
+----+ +----+----+----+
| | | 44 | 45 | 46 |
| | ----> | | | |
+----+ +----+----+----+
Array of pointers two dimensional array of three integers
to array of 3

如何声明 ptr_array,以便

ptr_array[0] = A;

ptr_array[1] = A + 1;

最佳答案

C 中的多维数组是数组的数组。 n 维数组的元素是 (n-1) 维数组。例如,A[0] 是一个 int [3]

A:    |24|25|26|44|45|46|A[0]: |24|25|26|A[1]: |44|45|46|

In certain contexts, an array is converted to a pointer to the first element of the array, but the array is not itself a pointer.

From the C standard, § 6.5.2.1-3:

3 Successive subscript operators designate an element of a multidimensional array object. If E is an n-dimensional array (n≥2) with dimensions i× j×...×k, then E (used as other than an lvalue) is converted to a pointer to an (n − 1)-dimensional array with dimensions j × . . . × k. If the unary * operator is applied to this pointer explicitly, or implicitly as a result of subscripting, the result is the pointed-to (n − 1)-dimensional array, which itself is converted into a pointer if used as other than an lvalue. It follows from this that arrays are stored in row-major order (last subscript varies fastest).

4 EXAMPLE Consider the array object defined by the declaration

int x[3][5];

Here x is a 3 × 5 array of ints; more precisely, x is an array of three element objects, each of which is an array of five ints. In the expression x[i], which is equivalent to (*((x)+(i))), x is first converted to a pointer to the initial array of five ints. Then i is adjusted according to the type of x, which conceptually entails multiplying i by the size of the object to which the pointer points, namely an array of five int objects. The results are added and indirection is applied to yield an array of five ints. When used in the expression x[i][j], that array is in turn converted to a pointer to the first of the ints, so x[i][j] yields an int.

To create a ptr_array as diagrammed:

int (*ptr_array[2])[3]
ptr_array[0] = A;
ptr_array[1] = A+1;
// or:
ptr_array[0] = &A[0];
ptr_array[1] = &A[1];
// or even:
ptr_array[0] = (int(*)[3])A[0];
ptr_array[1] = (int(*)[3])A[1];
// though this last shouldn't be used in production code

下面是如何制定声明。从图中可以看出,ptr_array 是一个大小为 2 的数组。

... ptr_array[2] ...

数组的元素是指针

*ptr_array[2]

到大小为 3 的数组

(*ptr_array[2])[3]

整数

int (*ptr_array[2])[3]

如果你不确定如何声明这样的东西,你可以使用 cdecl :

cdecl> declare ptr_array as array 2 of pointer to array 3 of intint (*ptr_array[2])[3]

您可以在开发计算机上安装命令行版本的 cdecl(如果尚未安装)。具体方法取决于平台。全面检查文档和网络。

关于c - 指向 int 数组的指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8704724/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com