Initialization of Two-Dimensional String Array-dynamic memory allocation

Source: Internet
Author: User

# Include "stdio. H"

Void main ()

{

Char * str1 [2] [2] = {"FF", "F9", "Fa", "F9"}; // initialize a Two-Dimensional String Array

Char * STR; // defines a one-dimensional string variable.

Int A, B;

Int I, J;

Int result1;

For (I = 0; I <2; I ++)

{

For (j = 0; j <2; j ++)

{

STR = str1 [I] [J]; // assign values to one-dimensional strings

Printf ("% s/n", STR );

If (str [0]> = 'A' & str [1]> = 'A ')

{

A = int (str [0]-'A ');

B = int (str [1]-'A ');

Result1 = (a + 10) * 16 + (B + 10) * 1; // "AA "~ Conversion results between "FF"

}

Else if (str [0]> = 'A' & str [1] <'A ')

{

A = int (str [0]-'A ');

B = 'a'-str [1] + 1;

Result1 = (a + 10) * 16 + B; // "A0 "~ Conversion results between "F9"

}

Else if (str [0] <'A' & str [1]> = 'A ')

{

A = 'a'-str [0] + 1;

B = int (str [1]-'A ');

Result1 = a * 16 + (B + 10) * 1; // "0A "~ Conversion results between "9F"

}

Else

{

A = 'a'-str [0] + 1;

B = 'a'-str [1] + 1;

Result1 = a * 16 + B; // "00 "~ Conversion Result between "99"

}

Printf ("a = % d/n", );

Printf ("B = % d/n", B );

Printf ("% d/n", result1 );

}

}

}

Here we just used a 2 × 2 String Array for an experiment. An image is relatively large, which will occupy a lot of memory during array initialization, in this way, compilation may sometimes fail. yesterday there were several crashes and only 64 × 64 arrays were used. Later, we put array initialization out of main and use it as a global variable to statically allocate a piece of memory space in the stack. Although feasible, it also occupies a lot of memory, so I thought about Dynamically allocating memory in the function and re-learning the dynamically allocated memory. If I don't know about it, I can study it with me.

Dynamic Memory Allocation

1. heap memory allocation:

C/C ++ defines four memory intervals: Code zone, global variable and static variable zone, local variable zone (stack zone), dynamic storage zone (heap) free store ).

Concept of heap:

A variable (or object) is usually defined. during compilation, the compiler can know the size of memory space according to the variable (or object) type, in this way, the system allocates specific storage space to them when appropriate. This memory allocation is called static storage allocation;

Some operation objects can be determined only when the program is running. In this way, the storage space cannot be reserved during compilation. The system allocates memory only when the program is running, this method is called dynamic storage allocation. All dynamic storage is allocated in the heap area.

When running a program to a variable or object that requires dynamic allocation, you must apply to the system for obtaining a storage space of the required size in the heap for storing the variable or object. When this variable or object is no longer used, that is, when its life ends, the storage space occupied by the variable or object needs to be explicitly released so that the system can allocate the heap space again, to reuse limited resources.

 

2. heap memory allocation and release

How to apply for and release a heap space:

In C ++, apply for and release the storage space allocated in the heap, and use the new and delete operators respectively: pointer variable name = new type name (initialization type );

Delete pointer name;

Example: 1. int * Pi = new int (0 );

It is roughly equivalent to the following code sequence:

2. Int ival = 0, * Pi = & ival;

Difference: the variable pointed to by PI is allocated by the library operator new (), located in the heap area of the program, and the object is not named.

Description of heap space application and release:

(1) the new operator returns a pointer to the allocated type variable (object. This pointer is used to indirectly operate the created variable or object, and the dynamically created object itself has no name.

(2. generally, when defining variables and objects, You need to name them with identifiers, named objects, and dynamic named unknown objects (note the difference between them and the temporary objects in the stack area. The two are completely different: different lifecycles, the operation method is different, and the temporary variables are transparent to the programmer ).

(3) The heap does not perform automatic initialization (including resetting) During allocation. Therefore, you must use initializer to explicitly initialize the heap. The Operation Sequence of the new expression is as follows: Allocate an object from the heap area, and then initialize the object with the value in brackets.

 

3. Demonstration of heap space application and release:

(1). Use initializer to explicitly initialize

Int * Pi = new int (0 );

(2) When the PI lifecycle ends, the target pointed to by the PI must be released:

Delete PI;

Note that at this time, the target memory space indicated by PI is released, that is, the target is revoked, and the dynamic memory is released (dynamic memory deallocation), but the pointer pi is not undo, it still exists, and the memory occupied by the pointer is not released.

The following describes the new operation.

(1) the new operator returns a pointer to the allocated type variable (object. This pointer is used for indirect operations on the created variables or objects, but the dynamically created object itself has no name.
(2. generally, when defining variables and objects, You need to name them with identifiers, named objects, and dynamic named unknown objects (note the difference between them and the temporary objects in the stack area. The two are completely different: different lifecycles, the operation method is different, and the temporary variables are transparent to the programmer ).

(3) The heap does not perform automatic initialization (including resetting) During allocation. Therefore, you must use initializer to explicitly initialize the heap. The Operation Sequence of the new expression is as follows: Allocate an object from the heap area, and then initialize the object with the value in brackets.

 
4. Create a dynamic one-dimensional array in the heap

① Apply for an array space:

Pointer variable name = new type name [subscript expression];

Note: "subscript expression" is not a constant expression, that is, its value does not need to be determined during compilation, but can be determined at runtime.

② Release the array space:

Delete [] pointer variable name pointing to this array;

Note: square brackets are very important. If square brackets are missing in the delete statement, because the compiler considers the pointer to be the first element of the array, incomplete collection will occur (only the space occupied by the first element is recycled). After square brackets are added, it is converted to a pointer to the array to recycle the entire array. The number of array elements is not required in square brackets of Delete. Even if it is written, the compiler ignores it.

# Include <iostream. h>

# Include <string. h>

Void main (){

Int N;

Char * PC;

Cout <"Enter the number of elements in the dynamic array" <endl;

Cin> n; // n is determined at runtime. Enter 17.

Pc = new char [n]; // apply for memory space of 17 characters (8 Chinese characters and an ending character can be loaded)

Strcpy (pc, "Dynamic heap memory allocation ");//

Cout <pc <endl;

Delete [] pc; // release the memory space of the pc pointing to n characters

Return ;}

 

5. Description of dynamic one-dimensional array

① The value of Variable n is not determined during compilation, but is input at runtime and heap space is allocated according to runtime. This is an advantage of dynamic allocation, it can overcome the disadvantages of array "Wide-opening and small-use" and provides algorithms in tables, sorting, and searching. If dynamic arrays are used, the versatility is better. Note: delete [] pc releases n characters, while delete pc releases only one character;

② If a char * pc1 is set to pc1 = p, delete [] pc1 can also be used to release the space. Although C ++ does not perform a boundary check on arrays, the size of allocated space for arrays is recorded during heap space allocation.

③ There is no initializer and arrays cannot be initialized.

6. pointer array and array pointer

Pointer type:

(1) int * ptr; // The Pointer Points to an int type.
(2) char * ptr; // The Pointer Points to a char type.
(3) int ** ptr; // The type pointed to by the pointer is int * (that is, an int * pointer)
(4) int (* ptr) [3]; // The type pointed to by the pointer is int () [3] // two-dimensional pointer Declaration

Pointer array:
A pointer of the same type is stored in an array, which is usually called a pointer array.

For example, int * a [2]; contains two int * type variables.

Int * a [2];
A [0] = new int [3];
A [1] = new int [3];
Delete a [0];
Delete a [1];

Note that this is an array and cannot be deleted [];

 

Array pointer:

A pointer to a one-dimensional or multi-dimensional array.

Int * B = new int [10]; pointer to the one-dimensional array B;
Note: delete [] is required to release space at this time. Otherwise, memory leakage will occur, and B will become an empty hanging pointer.

Int (* b2) [10] = new int [10] [10]; note that b2 points to the first address of a two-dimensional int array.
Note: Here, b2 is equivalent to a two-dimensional array name, but its boundary is not specified, that is, the number of elements in the highest dimension. However, the number of elements in the lowest dimension must be specified! Just like a pointer to a character, which is equivalent to a string, do not say a pointer to a character as a pointer to a string.

Int (* b3) [30] [20]; // Level 3 pointer-> pointer to a 3D array;
INT (* B2) [20]; // second-level pointer; --> pointer to a two-dimensional array;
B3 = new int [1] [20] [30];
B2 = new int [30] [20];
You can delete these two dynamic arrays as follows:
Delete [] B3; // Delete (release) a 3D array;
Delete [] B2; // Delete (release) two-dimensional array;
Create a dynamic multi-dimensional array in the heap

New type name [subscript expression 1] [subscript expression 2]……;

For example, creating a dynamic 3D Array

Float (* CP) [30] [20]; // point to a 30-row, 20-column Array

// Pointer to a two-dimensional array

CP = new float [15] [30] [20];

// Create an array consisting of 15 30*20 arrays;

Note: CP is equivalent to a 3D array name, but does not specify its boundary, that is, the number of elements in the highest dimension. It is like a pointer to a character that is equivalent to a string. Do not point to a character pointer, A pointer to a string. This is consistent with the nested definition of the array.

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.