Little Secrets of C language-Dynamic Array

Source: Internet
Author: User

The importance of the abstract is self-evident. Every time I publish an article, I am very entangled in how to write a special abstract, so that I can describe what I want to express to the readers in the simplest words. However, the most common problem is that the abstract is too short for readers to understand what the article is about; abstract: if you write a little longer, you will naturally be able to clearly describe what you want to express, but there is another problem, that is, the readers will see the text description of the paragraph, and feel boring, in other words, the article was sentenced to "death penalty". In this case, there are only a few readers willing to really spend time reading the abstract, let alone the text of the article, therefore, the greatest headache for writing an article is summarization.

Many people seldom use dynamic arrays when writing C language code. In any case, static arrays are used to solve the problem. I was a typical example when I first learned C language, however, it is found that this is a very bad habit, and may even cause some fatal errors in the program. Especially for Embedded users, the memory of the embedded system is precious. Whether the memory is used efficiently usually means whether the embedded devices are of high quality and high performance, therefore, it is very important for us to use memory efficiently. So we should learn to use dynamic arrays when writing C language code by ourselves, which is what I will tell you in this blog, I try my best to use some simple code to explain the dynamic array. I hope what I said will help you.

First, let's take a look at what a dynamic array is. A dynamic array is relative to a static array. We can also see its flexibility from the "dynamic" word. The length of a static array is predefined, in the entire program, once the given size cannot be changed. The dynamic array is not, it can be re-specified as the program needs. The memory space of the dynamic array is dynamically allocated from the heap. Is to allocate storage space for it by executing code. It is allocated only when the program runs the allocation statement we have compiled. Static arrays are easy to create and do not need to be released after use. It is easy to reference but cannot be changed after creation! For dynamic arrays, it is difficult to create and must be released by the programmer after use; otherwise, memory leakage will occur. However, it is flexible to use and can be dynamically allocated based on program needs. Therefore, compared with static arrays, we have a great degree of freedom to use dynamic arrays.

In the process of creating a dynamic array, we should follow the principle of creating layers from the outer layer to the internal layer during creation, and releasing layers from the internal layer to the outer layer during release. You may not have a deep understanding of this, but don't worry. Let's take a look at the two sections of code.

Create a one-dimensional dynamic array:

# Include <stdio. h>
# Include <stdlib. h>
Int main ()
{
Int N1, I;
Int * array;
Printf ("Enter the length of the one-dimensional dynamic array to be created :");
Scanf ("% d", & N1 );
Array = (int *) calloc (N1, sizeof (INT ));
For (I = 0; I <N1; I ++)
{
Printf ("% d \ t", array [I]);
}
Printf ("\ n ");
For (I = 0; I <N1; I ++)
{
Array [I] = I + 1;
Printf ("% d \ t", array [I]);
}
Free (array); // release the first-dimensional pointer
Return 0;
}

The running result is:

Note: I will attach the text results to the subsequent running results to prevent image opening failure.

Enter the length of the one-dimensional dynamic array to be created: 4
0 0 0 0
1 2 3 4 press any key to continue

Here I use the calloc () function for allocation, and also use two for statements to print array elements. We find that the value of the first output array element is 0, this is also to enhance the reader's impression on the calloc () function. I specifically use it for allocation. If you are interested in calloc (), malloc (), realloc () the difference between functions is quite clear. You can read my other blog ------ memory allocation of the little secrets in C language.

Create a two-dimensional array:

# Include <stdio. h>
# Include <stdlib. h>
Int main ()
{
Int N1, N2;
Int ** array, I, j;
Printf ("Enter the First-dimensional length of the dynamic array to be created :");
Scanf ("% d", & N1 );
Printf ("Enter the two-dimensional length of the dynamic array to be created :");
Scanf ("% d", & N2 );
Array = (INT **) malloc (N1 * sizeof (int *); // The first dimension
For (I = 0; I <N1; I ++)
{
Array [I] = (int *) malloc (N2 * sizeof (INT); // The second-dimensional
}
For (I = 0; I <N1; I ++)
{
For (j = 0; j <N2; j ++)
{
Array [I] [J] = I * N2 + J + 1;
Printf ("% d \ t", array [I] [J]);
}
Printf ("\ n ");
}
For (I = 0; I <N1; I ++)
{
Free (array [I]); // releases the second-dimensional pointer.
}
Free (array); // release the first-dimensional pointer
Return 0;
}

The running result is:

Enter the first-dimension length of the dynamic array to be created: 3
Enter the 2D length of the dynamic array to be created: 3
1 2 3
4 5 6
7 8 9
Press any key to continue

With the above Code, it is easy to create a dynamic array. Taking two-dimensional as an example, let's first create a dynamic array. Remember the principle we mentioned above: from the outer layer to the inside layer, layer-by-layer creation.

Array = (INT **) malloc (N1 * sizeof (int *); // The first dimension

The above is the outermost layer of the Two-dimensional dynamic array. After the outermost layer is created, we will create the outer layer.

Array [I] = (int *) malloc (N2 * sizeof (INT); // The second-dimensional

In the process of creating the outer layer, we use a for-like statement. Do not forget to use the for loop statement. This is a mistake for most people.

After the creation, let's talk about release. When it is released, it is released layer by layer to the outer layer. Just opposite to the above creation, in the above Code, we first use the following for loop to release the layer.

For (I = 0; I <N1; I ++)
{
Free (array [I]); // releases the second-dimensional pointer.
}

Use the following statement to release the outer layer.
Free (array); // release the first-dimensional pointer

If there is a multi-dimensional problem, let's take a look at the creation and release of a three-dimensional dynamic array to deepen the reader's impression. The Code is as follows:

# Include <stdlib. h>
# Include <stdio. h>
Int main ()
{
Int N1, N2, N3;
Int *** array;
Int I, J, K;
Printf ("Enter the First-dimensional length of the dynamic array to be created :");
Scanf ("% d", & N1 );
Printf ("Enter the two-dimensional length of the dynamic array to be created :");
Scanf ("% d", & N2 );
Printf ("Enter the 3D length of the dynamic array to be created :");
Scanf ("% d", & N3 );
Array = (INT ***) malloc (N1 * sizeof (INT ***); // The first dimension
For (I = 0; I <N1; I ++)
{
Array [I] = (INT **) malloc (N2 * sizeof (int *); // The second-dimensional
For (j = 0; j <N2; j ++)
{
Array [I] [J] = (int *) malloc (N3 * sizeof (INT); // 3D
}
}
For (I = 0; I <N1; I ++)
{
For (j = 0; j <N2; j ++)
{
For (k = 0; k <N3; k ++)
{
Array [I] [J] [k] = I + J + k + 1;
Printf ("% d \ t", array [I] [J] [k]);
}
Printf ("\ n ");
}
Printf ("\ n ");
}
For (I = 0; I <N1; I ++)
{
For (j = 0; j <N2; j ++)
{
Free (array [I] [J]); // release the 3D pointer
}
}
For (I = 0; I <N1; I ++)
{
Free (array [I]); // releases the second-dimensional pointer.
}
Free (array); // release the first-dimensional pointer
Return 0;
}

The running result is:

Enter the first-dimension length of the dynamic array to be created: 3
Enter the 2D length of the dynamic array to be created: 3
Enter the 3D length of the dynamic array to be created: 3
1 2 3
2 3 4
3 4 5

2 3 4
3 4 5
4 5 6

3 4 5
4 5 6
5 6 7

Press any key to continue

After reading the code for creating and releasing 3D dynamic arrays, I think you can write dynamic arrays of any dimension by yourself. However, careful readers may find a problem, that is, the dynamic arrays we are talking about are all created at one time, what if the array we use needs to be expanded or removed to remove elements that are no longer used ?! Next, let's take a look at the code for dynamic array expansion. Here we take the expansion of one-dimensional dynamic array as an example, and so on.

# Include <stdio. h>
# Include <stdlib. h>
Int main ()
{
Int * n, * P;
Int I, N1, N2;
Printf ("Enter the length of the dynamic array to be created :");
Scanf ("% d", & N1 );
N = (int *) calloc (N1, sizeof (INT ));
Printf ("Enter the length of the dynamic array to be extended :");
Scanf ("% d", & N2 );
P = (int *) realloc (n, (N2) * sizeof (INT); // dynamically expand the Array
For (I = 0; I <N2; I ++)
{
P [I] = I + 1;
If (I % 5 = 0)
Printf ("\ n ");
Printf ("% d \ t", P [I]);
}
Free (P );
Return 0;
}

The running result is as follows:

Enter the length of the dynamic array to be created: 6
Enter the length of the dynamic array to be extended: 25

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25 press any key to continue

After reading the code above, readers should know how to expand dynamic arrays. Some readers may be unfamiliar with the use of realloc () functions, if you have any questions, refer to a blog post I wrote earlier-memory allocation for the little secrets in C language. I will not explain it too much here.

Next, how to narrow down the dynamic array.

# Include <stdio. h>
# Include <stdlib. h>
Int main ()
{
Int * n, * P;
Int I, N1, N2;
Printf ("Enter the length of the dynamic array to be created :");
Scanf ("% d", & N1 );
N = (int *) calloc (N1, sizeof (INT ));
For (I = 0; I <N1; I ++)
{
N [I] = I + 1;
If (I % 5 = 0)
Printf ("\ n ");
Printf ("% d \ t", N [I]);
}
Printf ("\ n enter the length of the dynamic array to be reduced :");
Scanf ("% d", & N2 );
P = (int *) realloc (n, (N2) * sizeof (INT ));
For (I = 0; I <N2; I ++)
{
If (I % 5 = 0)
Printf ("\ n ");
Printf ("% d \ t", P [I]);
}
Printf ("\ n ");
Free (P );
Return 0;
}

The running result is:

Enter the length of the dynamic array to be created: 25

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
Enter the length of the dynamic array to be reduced: 15

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
Press any key to continue

It is worth noting that when the dynamic array is reduced, it deletes the following elements while the previous elements remain unchanged. When using the realloc () function, pay attention to its usage rules.

This is the time to end. Due to my limited level, it is inevitable that blog posts are inappropriate or wrong. I hope readers will criticize and correct them. Readers are also welcome to discuss relevant content. If you are willing to share your comments, please leave your valuable comments.

The importance of the abstract is self-evident. Every time I publish an article, I am very entangled in how to write a special abstract, so that I can describe what I want to express to the readers in the simplest words. However, the most common problem is that the abstract is too short for readers to understand what the article is about; abstract: if you write a little longer, you will naturally be able to clearly describe what you want to express, but there is another problem, that is, the readers will see the text description of the paragraph, and feel boring, in other words, the article was sentenced to "death penalty". In this case, there are only a few readers willing to really spend time reading the abstract, let alone the text of the article, therefore, the greatest headache for writing an article is summarization.

Many people seldom use dynamic arrays when writing C language code. In any case, static arrays are used to solve the problem. I was a typical example when I first learned C language, however, it is found that this is a very bad habit, and may even cause some fatal errors in the program. Especially for Embedded users, the memory of the embedded system is precious. Whether the memory is used efficiently usually means whether the embedded devices are of high quality and high performance, therefore, it is very important for us to use memory efficiently. So we should learn to use dynamic arrays when writing C language code by ourselves, which is what I will tell you in this blog, I try my best to use some simple code to explain the dynamic array. I hope what I said will help you.

First, let's take a look at what a dynamic array is. A dynamic array is relative to a static array. We can also see its flexibility from the "dynamic" word. The length of a static array is predefined, in the entire program, once the given size cannot be changed. The dynamic array is not, it can be re-specified as the program needs. The memory space of the dynamic array is dynamically allocated from the heap. Is to allocate storage space for it by executing code. It is allocated only when the program runs the allocation statement we have compiled. Static arrays are easy to create and do not need to be released after use. It is easy to reference but cannot be changed after creation! For dynamic arrays, it is difficult to create and must be released by the programmer after use; otherwise, memory leakage will occur. However, it is flexible to use and can be dynamically allocated based on program needs. Therefore, compared with static arrays, we have a great degree of freedom to use dynamic arrays.

In the process of creating a dynamic array, we should follow the principle of creating layers from the outer layer to the internal layer during creation, and releasing layers from the internal layer to the outer layer during release. You may not have a deep understanding of this, but don't worry. Let's take a look at the two sections of code.

Create a one-dimensional dynamic array:

# Include <stdio. h>
# Include <stdlib. h>
Int main ()
{
Int N1, I;
Int * array;
Printf ("Enter the length of the one-dimensional dynamic array to be created :");
Scanf ("% d", & N1 );
Array = (int *) calloc (N1, sizeof (INT ));
For (I = 0; I <N1; I ++)
{
Printf ("% d \ t", array [I]);
}
Printf ("\ n ");
For (I = 0; I <N1; I ++)
{
Array [I] = I + 1;
Printf ("% d \ t", array [I]);
}
Free (array); // release the first-dimensional pointer
Return 0;
}

The running result is:

Note: I will attach the text results to the subsequent running results to prevent image opening failure.

Enter the length of the one-dimensional dynamic array to be created: 4
0 0 0 0
1 2 3 4 press any key to continue

Here I use the calloc () function for allocation, and also use two for statements to print array elements. We find that the value of the first output array element is 0, this is also to enhance the reader's impression on the calloc () function. I specifically use it for allocation. If you are interested in calloc (), malloc (), realloc () the difference between functions is quite clear. You can read my other blog ------ memory allocation of the little secrets in C language.

Create a two-dimensional array:

# Include <stdio. h>
# Include <stdlib. h>
Int main ()
{
Int N1, N2;
Int ** array, I, j;
Printf ("Enter the First-dimensional length of the dynamic array to be created :");
Scanf ("% d", & N1 );
Printf ("Enter the two-dimensional length of the dynamic array to be created :");
Scanf ("% d", & N2 );
Array = (INT **) malloc (N1 * sizeof (int *); // The first dimension
For (I = 0; I <N1; I ++)
{
Array [I] = (int *) malloc (N2 * sizeof (INT); // The second-dimensional
}
For (I = 0; I <N1; I ++)
{
For (j = 0; j <N2; j ++)
{
Array [I] [J] = I * N2 + J + 1;
Printf ("% d \ t", array [I] [J]);
}
Printf ("\ n ");
}
For (I = 0; I <N1; I ++)
{
Free (array [I]); // releases the second-dimensional pointer.
}
Free (array); // release the first-dimensional pointer
Return 0;
}

The running result is:

Enter the first-dimension length of the dynamic array to be created: 3
Enter the 2D length of the dynamic array to be created: 3
1 2 3
4 5 6
7 8 9
Press any key to continue

With the above Code, it is easy to create a dynamic array. Taking two-dimensional as an example, let's first create a dynamic array. Remember the principle we mentioned above: from the outer layer to the inside layer, layer-by-layer creation.

Array = (INT **) malloc (N1 * sizeof (int *); // The first dimension

The above is the outermost layer of the Two-dimensional dynamic array. After the outermost layer is created, we will create the outer layer.

Array [I] = (int *) malloc (N2 * sizeof (INT); // The second-dimensional

In the process of creating the outer layer, we use a for-like statement. Do not forget to use the for loop statement. This is a mistake for most people.

After the creation, let's talk about release. When it is released, it is released layer by layer to the outer layer. Just opposite to the above creation, in the above Code, we first use the following for loop to release the layer.

For (I = 0; I <N1; I ++)
{
Free (array [I]); // releases the second-dimensional pointer.
}

Use the following statement to release the outer layer.
Free (array); // release the first-dimensional pointer

If there is a multi-dimensional problem, let's take a look at the creation and release of a three-dimensional dynamic array to deepen the reader's impression. The Code is as follows:

# Include <stdlib. h>
# Include <stdio. h>
Int main ()
{
Int N1, N2, N3;
Int *** array;
Int I, J, K;
Printf ("Enter the First-dimensional length of the dynamic array to be created :");
Scanf ("% d", & N1 );
Printf ("Enter the two-dimensional length of the dynamic array to be created :");
Scanf ("% d", & N2 );
Printf ("Enter the 3D length of the dynamic array to be created :");
Scanf ("% d", & N3 );
Array = (INT ***) malloc (N1 * sizeof (INT ***); // The first dimension
For (I = 0; I <N1; I ++)
{
Array [I] = (INT **) malloc (N2 * sizeof (int *); // The second-dimensional
For (j = 0; j <N2; j ++)
{
Array [I] [J] = (int *) malloc (N3 * sizeof (INT); // 3D
}
}
For (I = 0; I <N1; I ++)
{
For (j = 0; j <N2; j ++)
{
For (k = 0; k <N3; k ++)
{
Array [I] [J] [k] = I + J + k + 1;
Printf ("% d \ t", array [I] [J] [k]);
}
Printf ("\ n ");
}
Printf ("\ n ");
}
For (I = 0; I <N1; I ++)
{
For (j = 0; j <N2; j ++)
{
Free (array [I] [J]); // release the 3D pointer
}
}
For (I = 0; I <N1; I ++)
{
Free (array [I]); // releases the second-dimensional pointer.
}
Free (array); // release the first-dimensional pointer
Return 0;
}

The running result is:

Enter the first-dimension length of the dynamic array to be created: 3
Enter the 2D length of the dynamic array to be created: 3
Enter the 3D length of the dynamic array to be created: 3
1 2 3
2 3 4
3 4 5

2 3 4
3 4 5
4 5 6

3 4 5
4 5 6
5 6 7

Press any key to continue

After reading the code for creating and releasing 3D dynamic arrays, I think you can write dynamic arrays of any dimension by yourself. However, careful readers may find a problem, that is, the dynamic arrays we are talking about are all created at one time, what if the array we use needs to be expanded or removed to remove elements that are no longer used ?! Next, let's take a look at the code for dynamic array expansion. Here we take the expansion of one-dimensional dynamic array as an example, and so on.

# Include <stdio. h>
# Include <stdlib. h>
Int main ()
{
Int * n, * P;
Int I, N1, N2;
Printf ("Enter the length of the dynamic array to be created :");
Scanf ("% d", & N1 );
N = (int *) calloc (N1, sizeof (INT ));
Printf ("Enter the length of the dynamic array to be extended :");
Scanf ("% d", & N2 );
P = (int *) realloc (n, (N2) * sizeof (INT); // dynamically expand the Array
For (I = 0; I <N2; I ++)
{
P [I] = I + 1;
If (I % 5 = 0)
Printf ("\ n ");
Printf ("% d \ t", P [I]);
}
Free (P );
Return 0;
}

The running result is as follows:

Enter the length of the dynamic array to be created: 6
Enter the length of the dynamic array to be extended: 25

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25 press any key to continue

After reading the code above, readers should know how to expand dynamic arrays. Some readers may be unfamiliar with the use of realloc () functions, if you have any questions, refer to a blog post I wrote earlier-memory allocation for the little secrets in C language. I will not explain it too much here.

Next, how to narrow down the dynamic array.

# Include <stdio. h>
# Include <stdlib. h>
Int main ()
{
Int * n, * P;
Int I, N1, N2;
Printf ("Enter the length of the dynamic array to be created :");
Scanf ("% d", & N1 );
N = (int *) calloc (N1, sizeof (INT ));
For (I = 0; I <N1; I ++)
{
N [I] = I + 1;
If (I % 5 = 0)
Printf ("\ n ");
Printf ("% d \ t", N [I]);
}
Printf ("\ n enter the length of the dynamic array to be reduced :");
Scanf ("% d", & N2 );
P = (int *) realloc (n, (N2) * sizeof (INT ));
For (I = 0; I <N2; I ++)
{
If (I % 5 = 0)
Printf ("\ n ");
Printf ("% d \ t", P [I]);
}
Printf ("\ n ");
Free (P );
Return 0;
}

The running result is:

Enter the length of the dynamic array to be created: 25

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
Enter the length of the dynamic array to be reduced: 15

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
Press any key to continue

It is worth noting that when the dynamic array is reduced, it deletes the following elements while the previous elements remain unchanged. When using the realloc () function, pay attention to its usage rules.

This is the time to end. Due to my limited level, it is inevitable that blog posts are inappropriate or wrong. I hope readers will criticize and correct them. Readers are also welcome to discuss relevant content. If you are willing to share your comments, please leave your valuable comments.

Related Article

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.