C + + Two-dimensional array delivery

Source: Internet
Author: User

C + + Two-dimensional array delivery

When we pass a two-dimensional array, there may be some problems for the novice, and here are some of the delivery methods

When explaining how to pass a two-dimensional array, first look at how dynamic new two-dimensional arrays

1 //Dynamic application of two-dimensional array2     intRow, col;3CIN >> Row >>Col;4     5     int**arr;6     //C + + form7arr =New int*[row];8      for(inti =0; i<row;i++)9Arr[i] =New int[col];Ten      One     //C Form AArr = (int**)malloc(sizeof(int*) *row); -      for(inti =0; i<row;i++) -Arr[i] = (int*)malloc(sizeof(int) * col);

This method defines a level two pointer, and a level two pointer to an array element that is an integer pointer. And then the new array of the shaping pointer, so that the two-dimensional array is dynamic new.

Here is how to see the type of a variable, in C + +, by including the #include<typeinfo> header file, it is easy to print out the variable type, the following statement:

cout << typeid (variable_name) << Endl;

  

The following explains how to pass, if the two-dimensional array variable is a pointer form, then directly define the following function parameter is good

void Function_name (int** arr,int row,int col);

If the two-dimensional array variable is an array, it can be passed by casting to the int** form, such as the following code in the main function:

  

int Main (intconstChar * argv[]) {    int a[2] [2 ];    Function_name (int* *) A,2,2);}

This method of coercion can also be used for reference.

Another way to pass is to define the template as follows:

Template<typename t>void test1 (t& b) {    << typeid (b). Name () << Endl;} int Main (intconstChar * argv[]) {    int a[2] [ 2 ];     << typeID (a). Name () <<Endl;    Test1 (a);}

The above program is the same as the printing results, indicating that the template type derivation of B is deduced into a two-dimensional array type.

C + + Two-dimensional array delivery

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.