Connect with us

Dynamic Memory Allocation in C

Discussion in 'Microcontrollers, Programming and IoT' started by champ1, Apr 20, 2020.

Scroll to continue with content
  1. champ1

    champ1

    36
    0
    Jul 17, 2018
    Hi guys,
    I looked on the internet that dynamic memory allocation is not suitable for small Microcontroller But I need to understand the information given in this page https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/

    I am trying to understand following paragraph
    "
    As it can be seen that the length (size) of the array above made is 9. But what if there is a requirement to change this length (size). For Example,
    • If there is a situation where only 5 elements are needed to be entered in this array. In this case, the remaining 4 indices are just wasting memory in this array. So there is a requirement to lessen the length (size) of the array from 9 to 5.
    • Take another situation. In this, there is an array of 9 elements with all 9 indices filled. But there is a need to enter 3 more elements in this array. In this case 3 indices more are required. So the length (size) of the array needs to be changed from 9 to 12.
    "

    There is no such example coming in my mind that changes the length of array. What are the real time situation where length of array may be change ?
     
    Last edited: Apr 20, 2020
  2. Harald Kapp

    Harald Kapp Moderator Moderator

    10,069
    2,150
    Nov 17, 2011
    The quote gives you two examples...
    Other examples:
    - Strings (which in C are arrays of charcters) of varying length
    - Databases with varying content
    etc.
    If you don't have a need to use arrays of variable length, don't use them.
     
    champ1 likes this.
  3. champ1

    champ1

    36
    0
    Jul 17, 2018
    I know when size of array is fixed we should use static memory and when size of variable we should use dynamic memory, there is no misunderstanding to understand basic difference

    This example make sense, Every person has a different name The user does not know the exact length of string to store, so dynamic memory will use to store name of different person
     
Ask a Question
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.
Electronics Point Logo
Continue to site
Quote of the day

-