C ++ creates a dynamic two-dimensional array

Source: Internet
Author: User

C ++ has two main ways to create a dynamic two-dimensional array: 1. use an array pointer to allocate a pointer array, store its first address in B, and then assign an array int ** B = new int * [row] to each element of the pointer array; // allocate a pointer array and save its first address in B for (I = 0; I <row; I ++) // assign an array B [I] = new int [col] to each element of the pointer array; to release a dynamic two-dimensional array defined in this method, you must first release the array pointed to by each element of the pointer array, and then release the pointer array: for (I = 0; I <row; I ++) {delete [col] B [I]; B [I] = NULL;} delete [row] B; B = NULL;

Int _ tmain (int argc, _ TCHAR * argv []) {int row, column; cin> row> column; // method 1 // apply for a space int ** a = new int * [row]; for (int I = 0; I <row; I ++) a [I] = new int [column]; // use space for (int j = 0; j <row; j ++) for (int k = 0; k <column; k ++) a [j] [k] = rand () % 100; for (int j = 0; j <row; j ++) {cout <endl; for (int k = 0; k <column; k ++) {a [j] [k] = rand () % 100; cout <a [j] [k] <";}}// release space for (int I = 0; I <row; I ++) {delete a [I]; a [I] = NULL;} delete [row] a; a = NULL; return 0 ;}

 

Running result: 2. Use vector
Int _ tmain (int argc, _ TCHAR * argv []) {int row, column; cin> row> column; // method 2 // apply for Space vector <int> a (row, vector <int> (column); // use space for (int j = 0; j <row; j ++) for (int k = 0; k <column; k ++) a [j] [k] = rand () % 100; for (int j = 0; j <row; j ++) {cout <endl; for (int k = 0; k <column; k ++) {a [j] [k] = rand () % 100; cout <a [j] [k] <";}} return 0 ;}

 

The running result is:

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.