Accessing a two-dimensional array with a pointer

Preface
How to understand two-dimensional array? We understand a two-dimensional array in a two-dimensional way, but it is one-dimensional when it is stored.

Use a pointer to access a two-digit array
Example: int a[3] [4] = {1,3,5,7,9,11,13,15,17,19,21,23};

a[0] [0] a[0] [1] a[0] [2] a[0] [3] a[1] [0] a[1] [1] a[1
] [2] a [1] [3]
a[2] [0] a[2] [1] a[2] [2] a[2] [3] The storage method of our imagined
two-dimensional array: 3 rows and 4 columns

a[0] [0]
a[0] [1]
a[0] [2]
a[0] [3]
a[1] [0]
a[1] [1]
a[1] [2]
a [1] [3]
a[2] [0]
a[2] [1]
a[2] [2]
a[2] [3]
We think that the first four are an array name with a[0] One-bit array with four int elements

The middle four are one-dimensional arrays named a[1]

The last four are one-dimensional arrays named a[2]

 

 

 Different forms of accessing two-dimensional arrays through pointers

 

 

*a and a are two completely different concepts:

a treats this array as a one-dimensional array, and it adds one to the next one-dimensional array, namely a+1

*a points to a one-dimensional array where each element is an integer, so it is considered that *a+0 points to an integer, and adding one is the next integer

 

Why can't you use *p=a

int x,*p;
double y,*q;
p=&x;
q=&y;
p=q;//是错的
//p是指向四个字节为存储单元的地址
//q是指向八个字节为存储单元的地址
//两者不可以等价

 

Four ways to access two-dimensional array elements:

1. Access array elements by subscript

int a[3][4];
for (int i=0; i<3; i++)
    for (int j=0; j<4; j++)
        a[i][j] = i+j;

2. Access array elements through the first address of the array.
For a two-dimensional array element a[i] [j], “[]” is actually an indexing operator, which converts the storage address of the element a[i] [j] into a[ i] + j.

3. Access array elements through pointers ("view" a two-dimensional array from the perspective of a one-dimensional array")

int a[3][4];
int *p=&a[0][0];
for (int i=0; i<3; i++)
    for(int j=0; j<4; j++)
        *(p++) = i+j;        //相当于*p=i+j;p++;


Here, the pointer p is defined as: "pointer to int", that is to say: the p pointer "thinks" that it points to a one-dimensional array, each element is of type int, and there are 12 elements in total.

4. Access the array through a pointer ("view" the array from the perspective of a two-dimensional array)

int a[3][4]={1,3,5,7,9,11,13,15,17,19,21,23};
int (*p)[4];        
/*
对p指针的理解:
*p声明了p的指针。
p是指向什么的指针呢?
指向了一个包含了4个整数的一维数组
*/
p=a;
for(int i=0; i<3;i++)
    for (int j=0;j < 4;j++)
        *(*(p+i)+j)=i+j;

After the pointer is defined in this way, == pointer p will look at the two-dimensional array with exactly the same "perspective" as array a. ==That is to say, how a can be used, p can also be used in the same way

//For example: here *(*(p+i)+j) is replaced by p[i][j], a[i][j], *(*(a+i)+j) are all equivalent 1 points to a two-dimensional array of strings char *str[3]={"Red","Green","Blue"};//The priority of square brackets is higher than that of "*"//It
means str It is an array with three elements, which stores pointers to characters


 


Example: The scores of 3 students and 4 homework are stored in the student score array

Calculate the average of all grades for all students by calling the average function

Display the grades of the nth student's 4 homework by calling the search function.

Ideas:

A two-dimensional array score needs to be defined, and each row stores the grades of a student's 4 homework. If there are 3 rows, the grades of 3 students are stored.

65 70 70 60
80 87 90 81
90 99 100 98
When writing the function average to calculate the average score of all students, you can look at the score array from the perspective of a one-dimensional array, that is, "think" that the array has 12 Scores, sum directly, and calculate the average score on the line

When writing the function search to display the 4 homework of the nth student, use the perspective of a two-dimensional array to look at the score array, that is, "think" that the array has 3 rows, each with 4 elements

void average(float *p,int n)
{
    //以一维数组的方式看待学生成绩
    float *p_end;
    float sum=0,aver;
    p_end=p+n;
    for ( ; p<p_end;p++)
        sum=sum+(*p);
    aver=sum/n;
    printf("平均成绩为:%5.1f\n",aver);
}
void search(float (*p)[4],int n)//可以写成 float p[][4]
{
    //以二维数组的方式看待学生成绩,视角与score相同
    int i;
    printf("第%d个学生的成绩为: ",n);
    for (i=0;i<4;i++)
        printf("%5.1f",*(*(p+n)+i));  //可以替换成p[n][i]
}

int main()
{
    float score[3][4]={
   
   {65,67,70,60},{80,87,90,81},{90,99,100,98}};
    average(&score[0][0],12);        //可以替换成score[0],*(score+0)
    search(score,2);
    return 0;
}


Thinking (if you don’t understand, please go back and read)
(1) The two-dimensional score array is passed to the function, why are the average function and the search function used in different ways when passing parameters?

average(&score[0][0],12);        //可以替换成score[0],*(score+0)
search(score,2);                //显示第二个学生的成绩


Two-dimensional array as the parameter of the function
1. "Look at" the two-dimensional array from the perspective of one-dimensional array

 

 2. "Look at" a one-dimensional array from the perspective of a two-dimensional array

 

 

Exercises after class
Description of the topic: Write an inverse function, the function of which is to re-store the values ​​in a 3*4 two-dimensional array in reverse order.

Example of program running results

Please enter a 3*4 two-dimensional array:

1 2 3 4

5 6 7 8

9 10 11 12

The result after storing in reverse order is:

12 11 10 9

8 7 6 5

4 3 2 1

hint:

This program has a variety of implementation ideas, try to use two methods to achieve

Answer
Method 1: View the program as a two-dimensional array:

 

 

void inverse(int a[][N],int b[][N])
{
    int i,j;
    for (i=0;i<M;i++)
        for (j=0;j<N;j++)
            b[M-i-1][N-j-1]=a[i][j]
}

int main()
{
    int a[M][N],b[M][N];
    int i,j;
    printf("请输入 %d*%d 的二维数组:\n",M,N);
    for (i=0;i<M;i++)
        for (j=0;j<N;j++)
            scanf("%d",&a[i][j]);
    inverse(a,b);
    printf("逆序存放后的结果为:\n");
    for (i=0;i<M;i++)
    {
        for (j=0;j<N;j++)
            printf("%d\t",b[i][j]);
    }
}

Method 2: View the program as a one-dimensional array: 

 

 

void swap(int *p1,int *p2)
{
    int tmp = *p1;
    *p1 = *p2;
    *p2 = tmp;
}

//以 int *a 这样的方式传参,使得在子程序中以一维的方式看待数组,
//也就是说,把数组看成了一个具有 M*N 个元素的,每个元素都是 int 的数组
void inverse(int *a,int n)
{
    int *p,*q;
    for (p=a,q=a+n-1;p<=q;p++,q--)
    {
        swap(p,q);
    }
}

int main()
{
    int a[M][N];
    int i,j;
    printf("请输入 %d * %d 的二维数组: \n");
    for (i=0;i<M;i++)
        for (j=0;j<M;j++)
            scanf("%d",&a[i][j]);
    inverse(&a[0][0],M*N);
    printf("逆序存放后的结果为: \n");
    for (i=0;i<M;i++)
    {
        for (j=0;j<N;j++)
            printf("%d\t",a[i][j]);
    	printf("\n");
    }
    return 0;
}

The program uses two constants M and N, such a program has good flexibility. 

————————————————
Copyright statement: This article is the original article of CSDN blogger "Zong Gu." It follows the CC 4.0 BY-SA copyright agreement. For reprinting, please attach the original source link and this article statement.
Original link: https://blog.csdn.net/Zonggu/article/details/124051465

Guess you like

Origin blog.csdn.net/modi000/article/details/131916851