Accessing a two-dimensional array through a level two pointer requires assigning a one-dimensional array pointer equal to the number of rows in a two-dimensional array, and then assigning each header of a two-dimensional array to a one-dimensional pointer in the corresponding position. It can then be accessed directly by a two-dimensional pointer.
Refer to the code below, you can see the specific annotation auxiliary understanding.
12345678910111213141516171819202122232425 |
#include <stdio.h>//输入输出头文件。
#include <stdlib.h>//本程序需要用到malloc/free函数,引用该头文件。
int
main()
{
int a[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12};
//定义二维数组a,并赋值从1-12.
int
** p = NULL;
//定义二维指针。
int
i, j;
p = (
int
**)
malloc
(
sizeof
(
int
*) *3);
//要访问的数组有三行,所以申请三个一维指针变量。
for
(i = 0; i < 3; i ++)
{
p[i] = a[i];
//将二维数组行地址赋值到对应的一维指针上。
}
for
(i = 0; i < 3; i ++)
{
for
(j = 0; j < 4; j ++)
printf
(
"%d "
, p[i][j]);
//用指针输出元素。p[i][j]这里也可以写作*(*(p+i) + j)。
printf
(
"\n"
);
//每行输出后加一个换行
}
free
(p);
//释放申请的内存。
return
0;
}
|
Using two-dimensional pointers to access two-dimensional arrays is used for function calls.
For a one-dimensional array, if the function parameter is a one-dimensional pointer, the array name can be used directly as a function parameter. However, if the function parameter is a two-dimensional pointer, the direct use of two-dimensional array names to make the parameter access error occurs because the two-dimensional pointers and two-dimensional arrays are accessed differently, you need to do the conversion in the sample code.
Another common method is to use the memory continuity of a two-dimensional array to convert a two-dimensional array to a one-dimensional array, regardless of the subject matter, without any further description.
Https://zhidao.baidu.com/question/585729445.html
How to operate a two-dimensional array with level two pointers in C language