Dynamically allocate two-dimensional arrays in C

Source: Internet
Author: User

From: http://tsindahui.blog.sohu.com/84512010.html

It is easy to dynamically allocate memory in C for a single variable, string, and one-dimensional array. The method for dynamically allocating two-dimensional arrays in C is rarely described in the C language. I found a method mentioned in some C language books:

Assume that the dimension of the Two-dimensional array is [m] [N].

The allocation is as follows:
Int ** PTR = new int * [m]; // This is an array with M pointers first, that is, a needle array is allocated first.

///////// The first address of the pointer array is saved in PTR.
For (INT I = 0; I <m; I ++)
PTR [I] = new int [N]; // assign an address to each element of the pointer array,

/// This address is the address pointing to the one-dimensional array, that is, assigning an array for each element of the needle element array.

An example of source code is:

Int ** pmatrix = new int * [row];

For (INT I = 0; I <row; I ++)
{
Pmatrix [I] = new int [column];

For (Int J = 0; j <column; j ++)
{
Pmatrix [I] [J] = (I + J); // simple Initialization

}

}

There is a serious problem in creating an array in this way, that is, its memory is not continuous and the memory between rows is not continuous. Although it can be accessed using [I] [J] subscript, unable to meet the requirements of using pointer variables pointing to the two-dimensional array element type to access the entire array

For example, you cannot access each two-dimensional array element as follows:

Int * P = NULL;

For (P = pmatrix [0]; P <pmatrix [0] + column * row; P ++)
{
Int fff = * (PME );

}

This access method is completely feasible for real two-dimensional arrays. This is because the memory between rows is not continuous.

Therefore, the dynamic two-dimensional array created in this method is not a real two-dimensional array.

So what is a real two-dimensional array? The two-dimensional array in C language is a continuous memory area stored by row in the memory organization form. Therefore, you must ensure that the array elements are stored by row, and the most important thing is that the memory needs to be continuous.

Therefore, I wrote the following method:

Assuming that the element variable type of a two-dimensional array is mytype, it can be any type accepted by C language except void, because the compiler does not know the size of the void type; for example, Int, float, double, and so on;

Int ROW = 2; // it is assumed that the number of rows is 2, which can be determined at runtime;
Int column = 3; // it is assumed that the number of columns is 2, which can be determined at runtime;

Void ** ptdhead = NULL; // The following describes why the void ** type is used.
Void ** ptdbody = NULL; // The following describes why the void ** type is used.

Ptdhead = (void **) malloc (sizeof (void *) * row + sizeof (mytype) * row * column );


If (! Ptdhead)
Return false;

Ptdbody = ptdhead + row;



For (INT ncount = 0; ncount <row; ncount ++)
Ptdhead [ncount] = ptdbody + ncount * column * sizeof (mytype)/sizeof (void *);

Mytype ** ptdheadrealse;
Ptdheadrealse = (mytype **) ptdhead; //////////////// forcibly convert the pointer to the two-dimensional array element type required by your program
Ptdhead = NULL;

For (INT I = 0; I <row; I ++)
{
For (Int J = 0; j <column; j ++)
{
Ptdheadrealse [I] [J] = I + J; // you can perform simple initialization;
}

}

This method dynamically allocates two-dimensional arrays. The memory is continuous. It is a true two-dimensional array of C language, satisfying all two-dimensional array access methods and high memory utilization efficiency, program performance is good.

The following concepts should be understood in such a allocation method:
Experience: as long as the pointer can carry [], both direct and indirect pointers can use subscript, as long as the pointer is OK, this is critical;
The other is to understand that the void * pointer cannot be used for addition or subtraction, because the system does not know the size of a void,
However, the void ** pointer can be used for addition and subtraction to offset the pointer, because the void * type size makes it known,
Therefore, the compiler allows you to calculate the offset address.
Void * P = (void *) malloc (3); the compiler cannot pass void * q = P + 3;

We know that assume that an integer variable ncont is 4 bytes on a 32-bit machine, Q is the pointer variable pointing to ncont, and the value of Q, that is, the address of ncont is 0x00032ec0, then the value of q + 1 is 0x0x00032ec0 + 1*4. This is the method for calculating the pointer expression value in C language. That is, the value of q + 1 is q + 1 * sizeof (INT );

From here, we can understand why we use void ** as the type returned by the dynamically allocated memory function, because if the return is of the void * type, we cannot calculate the address offset, that is, the address of the first element of the array cannot be calculated, that is, the address of the array. Of course, we can use a simple type embedded in any c Except void * Without void **. However, it is easy and convenient to use it, so I think it is still possible to use void ** or char *; To select the char * type, it is convenient that the char type is 1, then the number of elements is equal to the address offset.

The above is my opinion on Dynamic Allocation of two-dimensional arrays in C language. Thank you for your criticism.

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.