[C Language] Data Structure-preparation knowledge dynamic memory allocation, data structure dynamic memory

Source: Internet
Author: User

[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);
} 

 


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.