C language: using pointers to get the value of a two-dimensional array

 In C language, elements of arrays can be accessed using pointers. For a two-dimensional array, we usually think of it as an array of pointers to a one-dimensional array (here it needs to be emphasized that the addresses of the two-dimensional array are continuous )

For example, if we have a two-dimensional array arr, which contains 3 rows and 3 columns, we can define a pointer p pointing to this array:

#include<stdio.h>
int main() {
int arr[3][3]={1,4,7,8,9,6,3,2,5},*p;

//指针p指向数组的首个元素,也可以理解为首个地址
p=arr;
//接下来,我们可以使用指针来访问数组元素。例如,要访问第2行第2列的元素,可以使用以下代码:
int a=*(*(arr+1)+1);
printf("%d",a);
	return 0;
}

Among them, *(arr+1) points to the second row of the two-dimensional array, *(*(arr+1)+1) points to the second element of the row, and finally uses the * operator to obtain the value of the element

Here it is emphasized again: the address of the two-dimensional array is continuous

In some cases, it is more convenient and flexible to use pointers to access two-dimensional array elements.

Guess you like

Origin blog.csdn.net/weixin_63987141/article/details/129959816