Dynamic array of C language application

For people new to C language programming, often encounter this situation - "When we deal with such a problem, let's storage size or use a case with use of the user to change", then a lot of people started scratching their heads, do not know how to start. Today, I concluded some solutions in this regard, we hope that we can improve together.

Dynamic array:

First, we take a look at a set of codes:

_CRT_SECURE_NO_DEPRECATE #define 
 2 #include <stdio.h> 
 . 3 #include <stdlib.h> 
 . 4 void Create () { 
 . 5 n-int, I; 
 . 6 int * ARR; 
 . 7 Scanf ( "% D", & n-); 
 . 8 ARR = (int *) the malloc (the sizeof (int) * n-); 
 . 9 for (I = 0; I <n-; I ++) 
10 ARR [I] = I; 
. 11 for (I = 0; I <n-; I ++) 
12 is the printf ( "% D \ T", ARR [I]); 
13 is Free (ARR); 14} 15 16 int main () { . 17 Create (); 18 is return 0; . 19}

from the above code can be seen, for the array arr [], which is our personal use of the size of the input, rather than a beginning for a given, it is largely solved a given size to change the size of trouble.
And here it is to use the C language most commonly used malloc function for arr open space, but opened up a space must remember to free (), otherwise your memory will be because of these things to the full.
Second, the two-dimensional dynamic array:

Create void () {
int n-=. 3, m =. 4;
int ** A;
A = (int **) the malloc (the sizeof (int *) * n-); // creates an array of pointers, the array of pointers to the address assignment to A
for (int I = 0; I <n-; I ++)
A [I] = (int *) the malloc (the sizeof (int) * m); // allocate space for the second dimension

for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++)
a[i][j] = i + j;
}

for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++)
printf("%d\t",a[i][j]);
printf("\n");
}
}
int main(){
create();

return 0;
}

Simply put, is in accordance with the idea of ​​a two-dimensional array, two-dimensional arrays as one-dimensional array has a plurality of data in order to mimic the one-dimensional array can be established, where the use of the pointer to the way to further create.

 

Next it is for, when we first set up the size of the array is full when this case is the solution. Look at the code:

if (i == n) {

    // determine whether the array is full, if full, proceed as follows
    // The first step to apply a larger memory space for new space is twice as old space
    int * newSpace = (int *) malloc (sizeof (int) n-*) 2 *);
    // second step of copying data to the new space
    the memcpy (Newspace, ARR, n-* the sizeof (int));
    // third step of releasing the old memory space
    Free (ARR);
  }

Then you can easily use the array, do not worry about the array overflow occurs in the course, and only need to ensure that enough memory just fine.

Guess you like

Origin www.cnblogs.com/Justina/p/11432616.html