In C language, how can I pass an indefinite two-dimensional array as a parameter to a function?

Source: Internet
Author: User

Generally, when a two-dimensional array is passed to a function, the length of the second-dimensional array cannot be omitted.

Void fun (INT arr [] [6], int N)

In this case, the second dimension is fixed to death. But sometimes, we do need to process different two-dimensional arrays. Here is a clever method:

Considering that two-dimensional arrays are actually continuously stored, for example, arrays A [3] [4], then the elements followed by a [0] [3] are a [1] [0],

Based on this, you can use manual addressing to transmit an indefinite two-dimensional array to the function.

# Include <stdio. h> void fun (int * arr, int row, int col) {int I, j; for (I = 0; I <row; ++ I) {for (j = 0; j <Col; ++ J) printf ("% 4D", arr [I * Col + J]); printf ("\ n") ;}} int main () {int A [3] [4] ={{ 1, 2, 3, 4}, {5, 6, 7, 8 },{ 9, 10, 11, 12 }}; fun (int *) A, 3, 4); Return 0 ;}

Running result:

1 2 3 4

5 6 7 8

9 10 11 12


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.