Thread: A noob question - how to reduce the size of an array?

  1. #1
    Registered User
    Join Date
    Nov 2005

    A noob question - how to reduce the size of an array?


    i have declared an array of class point.

    point buffer[100];

    but somewhere during my program, it is known that the size is smaller, says size 50.

    how do i reduce the size of the buffer from there?

    Thanks in advance!!

  2. #2
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Out of scope
    C doesn't allow you to do that. Nor does C++. What you could do is dynamically allocate an array, put what you want in it, then when you get the size you want, transfer that data to a newly allocated array of the appropriate size and delete the old one.
    Sent from my iPadŽ

  3. #3
    Registered User fischerandom's Avatar
    Join Date
    Aug 2005
    SlyMaelstrom is right, that's the way to do it. But be aware that the technique he describes may fragment the heap and by doing so you might in practice end up with smaller free memory blocks in your heap which may have the effect that you can not allocate a memory block of a given size larger than the largest free block, even though the total amount of free memory is more than the block you try to allocate. That is if you don't use techniques such as handles (for example a char**) and use memory related functions for compacting the heap. Maby you should consider trying to do what SlyMaelstrom suggested only when you are out-of-memory.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Fixing my program
    By Mcwaffle in forum C Programming
    Replies: 5
    Last Post: 11-05-2008, 03:55 AM
  2. Array size
    By tigrfire in forum C Programming
    Replies: 5
    Last Post: 11-14-2005, 08:45 PM
  3. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM
  4. Replies: 11
    Last Post: 03-25-2003, 05:13 PM
  5. Class member array size with constuctor initalizer
    By rafe in forum C++ Programming
    Replies: 2
    Last Post: 10-14-2002, 10:09 AM