/* Static memory allocation: A[5] has always been 5, will not change, (you can also think that as long as the malloc () function is not used, is static memory allocation) This code is dynamic memory allocation: The MALLOC function dynamically changes the array memory, and malloc (20) returns the first address of the application memory. Usage: cast (int *) malloc (sizeof (int) * len) June 1, 2016 14:13:08 * * include <stdio.h> # include <malloc.h>//Note malloc () function to add header file int main (void) {int a[5] = {4, 10, 2, 8, 6}; Imagine the array memory allocation, a pointing to the a[0] address, a+2 to the a[2] address, * (a+2) representing the a[2] value.
The length of a[5] 5 is dead, which belongs to the static memory allocation.
Now need to allocate the memory or length of the array to modify, with the malloc function!
int Len;
printf ("Please enter the length size you want to assign to the a[] array: len ="); scanf ("%d", &len); Note that there is a take-address character ...
The input value is transmitted to the variable according to the variable address. int *parr = (int *) malloc (sizeof (int) * len);
malloc (20) to request a 20-byte memory, the malloc function returns the first byte address. The first byte address does not have much meaning, because you do not know whether the first address represents int, double, char or something.
I don't know how big the first element of the array is.
So to make a cast, (char *), (int *), (double *) can indicate what type of element is. /* Parr[0] = 4;
Equivalent to a[0] = 4; * (PARR + 1) = 10; Equivalent to parr[1] = 10;
, can be added down to the specified 20 (also can change AH), the array is not fixed length printf ("%d,%d\n", *parr, parr[1]);
//rewrite the above 3 lines of code, where we can use Parr as an ordinary array.
printf ("Enter the value of the array separately:"); for (int i=0; i<len; i++) {
scanf ("%d", &parr[i]);
Assign value to array} for (i=0 i<len; i++)//Note there is a problem with the C language: the previous for has already defined int I, here can not write int i,i already defined, cannot repeat definition ... printf ("%d", parr[i]); Output array all values//above is dynamic allocation, the following is dynamic release free (PARR);
To release the dynamically allocated 20 bytes of memory represented by Parr, be sure to pay attention to memory release, malloc the requested memory system will not be automatically released.
return 0;
}