[C Language] Data Structure-preparation knowledge dynamic memory allocation, data structure dynamic memory
Dynamic Memory Allocation
Static Memory Allocation array int a [5] = {1, 2, 3, 4, 5}
Dynamic Memory Allocation Array
Int len = 5;
Int * parr = (int *) malloc (sizeof (int) * len );
1. 4*5 = 20 bytes of memory is allocated, and the address of the first byte is returned.
2. The address of the first byte is meaningless, so it is forcibly converted to an int type address int *
3. parr points to the address of the first byte, which is equivalent to.
* Parr = 4 <=> a [0] = 4
Parr [1] <==> a [1]
4. release memory
Free (parr) releases the dynamically allocated 20 bytes of memory represented by parr.
#include <stdio.h>
#include <malloc.h>
int main (void) {
printf ("% s \ n", "Please enter the length of the array");
int len;
scanf ("% d", & len);
// Dynamic allocation of memory
int * parr = (int *) malloc (sizeof (int) * len);
int i;
for (i = 0; i <len; i ++) {
printf ("Element:");
scanf ("% d", & parr [i]); // Another way, * (parr + i)
}
for (i = 0; i <len; i ++) {
printf ("% d \ n", parr [i]); // Used as an ordinary array
}
// Free up memory
free (parr);
}