"C language" two-dimensional array to do formal parameters

Source: Internet
Author: User

Two-dimensional arrays are available as: ① on the stack: int a[4][4] = {...};          ② on heap: int * * = new int *[4]; for (int i = 0; i < 4; i++) A[i] = new INT[4]; In both cases, the two-dimensional array does not have the same parameters for the formal parameter. ① on the stackvoid Fun (int * A, int rownum, int colmunnum) //Parameter pass by one-dimensional pointer {    ...A[r * colmunnum + c] = ...; //Find the corresponding location according to the column calculation
}void Main (){int A[4][4] = {...};Fun (int *) A, 4, 4); //cast to one-dimensional pointer upon invocation
}   when the ② on the heapvoid Fun (int * * A, int rownum, int colmunnum) //Parameter pass by two-dimensional pointer {    ...A[r][c] = ...; //directly read the corresponding position
}void Main (){    int * * a = new int *[4];for (int i = 0; i < 4; i++)A[i] = new Int[4]; Fun (A, 4, 4); //Direct call
}   These two ways can not be used together, can be wrong. The specific reason is because:The two-dimensional array allocated on the ① stack is actually similar to a one-dimensional array, and all values are stored continuously. Even if int a[4][4] writes like this, A is also a pointer to an int (*) [4] type, not an int * *, that is, the content is continuously stored for every 4 line breaks;② the Allocated int * * a = new int *[4], its four pointers are assigned separately and the contents are discontinuous. Therefore, it is not possible to locate by R*colnum +c.  If the two-dimensional array on the heap is passed in the first way, the output is garbled because the wrong address was read.   And the two-dimensional array on the stack in the second way to transmit the error, read the unallocated memory space. Self-summed: http://www.cnblogs.com/dplearning/p/4631541.html

"C language" two-dimensional array to do formal parameters

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.