Use pointers to pass multi-dimensional arrays to functions and use pointers to reference and modify multi-dimensional arrays.

Source: Internet
Author: User

Use pointers to pass multi-dimensional arrays to functions and use pointers to reference and modify multi-dimensional arrays.

Define A double type two-dimensional array A and another double empty two-dimensional array B of the same size, write A function to copy data in A to B. And test the program.

 1 #include <stdio.h> 2 void copy_ptr(const double (*s)[12],double (*tar)[12],int row,int col); 3 int main(void){ 4     const double rain[5][12]={ 5         {4.3,4.3,4.3,3.0,2.0,1.2,0.2,0.2,0.4,2.4,3.5,6.6}, 6         {8.5,8.2,1.2,1.6,2.4,0.0,5.2,0.9,0.3,0.9,1.4,7.3}, 7         {9.1,8.5,6.7,4.3,2.1,0.8,0.2,0.2,1.1,2.3,6.1,8.4}, 8         {7.2,9.9,8.4,3.3,1.2,0.8,0.4,0.0,0.6,1.7,4.3,6.2}, 9         {7.6,5.6,3.8,2.8,3.8,0.2,0.0,0.0,0.0,1.3,2.6,5.2}10     },t1[5][12];11     copy_ptr(rain,t1,5,12);12     //printf("%.2f",t1[3][8]);13     return 0;14 }15 void copy_ptr(const double (*s)[12],double (*tar)[12],int row,int col){16     int i,j;17     for(i=0;i<row;i++){18         for(j=0;j<col;j++){19             *(*(tar+i)+j)=*(*(s+i)+j);20         }21     }22 }

In the function prototype and function definition, two-dimensional array parameters are written

double (*s)[12]

This indicates that the function accepts a pointer parameter pointing to an array with 12 double values ). That is, the sub-array.

Because the sub-array itself is a pointer to each single double value, the meaning of double (* s) [12] Here is "s is a pointer, it points to (the step size is 1 double, and the range is 0 ~ 11 pointer) ", and the s step is the total range of the pointer it points.

In summary, a multi-dimensional array actually implies a pointer tree behind the value. Or the pointer chain may be more accurate. When an address is not pointed to, the needle actually does not exist. At a time point, the pointer value path from top to bottom is always unique, so it is chained.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.