An example of the application of c language two-dimensional array pointer

 C language pointer application

#include <stdio.h>
//首先要明白数组的一些特性
//1.函数传递数组形参,只传输数组的指针,也就是指向数组元素的指针
//2.第二个参数类型就是一个二维数组,元素类型也就是int [7],所以指针也就是int (*)[7]
//3.传递的时候给一个二维数组的名字即可,数组的名字可以被当成是指向第一个元素的指针
void search(int *,int *,int array[24][7],int key);
//函数print_row_i的第一个参数也就是 int(*)[7],一会传递二维数组迭代
void print_row_i(int (*a)[7],int row);

int main()
{
int week,day,key;
//定义一个二维数组
int a[][7] = {
          {1,32,3,4,1,2,45},
	  {12,41,32,3,5,2,35},
	  {12,3,5,4,1,2,4},
	  {4,2,4,1,3,45,4},
	  {14,21,41,2,4,3,2},
	  {12,4,5,1,1,41,23},
	  {23,42,34,5,2,31,4}
           };
search(&week,&day,a,32);
print_row_i(a,3);
	return 0;
}

void search(int * week,int *day,int array[24][7],int key)
{
int i,*ptr,week_,day_;
int index = 0;
  for(ptr = &array[0][0]; ptr != &array[0][0] + 7*24 ; ++ptr)
    { index ++;
      if(*ptr == key)
      {
         *week = index / 7 + 1; 
     	 *day  = index % 7;   
          printf("week %d,day %d\n",*week,*day); 
      }
    }

}
void print_row_i(int (*a)[7],int row)
{
int (*p)[7];
p = a + row;
int *ptr;
//dereference from array can get a element type
//p是一个指向二维数组的元素类型的一直指针(每个元素都是int [7]),对p解引用就得到了一个
//二维数组的元素类型 int [7],也就是解引用得到了一个1维数组,也就是指向元素的类型的指针

for(ptr = (*p);ptr != (*p) + 7;++ptr)
	printf("%d ",*ptr);
}

to sum up:

1. The array parameter is passed the pointer of the array, which is the pointer to the array element

For example, if the array is int array[], then the element type is int, so the passed argument type is int *, just the array name

2. The array name is a pointer to its first element, for example 

int array[], the type of array is int *

int array[m][n], the type of each element is int [n], so the type of array is int(*)[n]

3. Dereferencing the int (*)[n] type will get, int [n] type, which is a pointer to each element of int [n]

For example, int(*p)[n]; p = array; int *ptr = *p; // dereference p here will get a one-dimensional array, which is also a pointer to the elements of the one-dimensional array, of course the int * type Of it.

The above is my own conclusion based on the multidimensional array. I don't know if it's right, anyway, it's okay to write in accordance with these conclusions when actually programming. I hope everyone criticizes and corrects

 

 

 

Guess you like

Origin blog.csdn.net/digitalkee/article/details/112062446