How are two-dimensional arrays used as function parameters?

Source: Internet
Author: User
Tags function prototype

 

If we need to write a function that handles a two-dimensional array, how should this function prototype be declared?

First, we should keep in mind that the array name is treated as its address, so the corresponding parameter is a pointer. For example, suppose the following code:

[CPP]View Plaincopy
    1. int Data[3][4] = {{1, 2, 3, 4}, {5, 5, 7, 8}, {9, 10, 11, 12}}
    2. int total = SUM (data, 3);
So how should the prototype of the Sun function be declared? Why is the number of rows 3 as a parameter instead of the number of columns 4 as parameters?

We can understand this: data is an array name, and the array has 3 elements. And these 3 elements themselves are an array of 4 int. So the type of data is a pointer to an array of 4 int.

So the correct sum prototype is as follows:

[CPP]View Plaincopy
    1. int sum ( int (*arr) [4], int size);
    2. The parentheses are necessary because the following declaration declares an array of four pointers to int instead of a pointer to an array of 4 int.
    3. int *arr[4]; //declares an array of pointers that contains 4 int pointer variables
    4. int (*arr) [4] //declares a pointer variable that points to an array of 4 int

There is another declarative format that is exactly the same as the correct prototype, but more readable:

[CPP]View Plaincopy
    1. int sum (int arr[][4], int size);

All 2 of these prototypes indicate that ARR is a pointer rather than an array. Also note that the meaning of the int arr [] [4] is: ARR is a pointer to an array of 4 int. Therefore, the pointer type specifies the number of columns, which means that the function parameter has determined the number of columns of the real parameter group, which is why the number of columns is not passed as a separate function argument.

How are two-dimensional arrays used as function parameters? (RPM)

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.