Thread: Dynamic Array Size

  1. #1
    Registered User
    Join Date
    Jul 2016
    Posts
    9

    Dynamic Array Size

    Hi, everyone. I need an array with a dynamic capacity. There's a loop that calls a function and the function generates values depending on the input user gives. The loop repeats as long as the function generates numbers. I want to keep those generated values in an array but I don't know if there will be 10 values or 1000 values, that depends on the user. What can I do to increase my array's capacity by 1 each time it repeats so there'll be room for one more result every single time. I guess I should use malloc() or realloc() but I can't exactly understand how. If you guys can post a simple example about it, I would be grateful. Thanks for your help. Have a good day

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Here is how you create expanding memory

    Start with
    Code:
    int currentIndex = 0;
    int maxSize = 0;
    int *mem = 0;
    Every time you want to store something in the array, you do this
    Code:
    if ( currentIndex == maxSize ) {
      int newsize;
      if ( maxSize == 0 ) newsize = 16;
      else newsize = maxSize * 2;
      void *t = realloc( mem, sizeof(*mem) * newsize );
      if ( t != NULL ) {
        mem = t;
        maxSize = newsize;
      } else {
        // panic
      }
    }
    mem[currentIndex] = ....
    ...
    currentIndex++;
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Jul 2016
    Posts
    9
    Thanks a lot. I'll write a function inspired by this and call it every time the loop repeats. Good day

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dynamic Array - Size
    By vijay s in forum C Programming
    Replies: 2
    Last Post: 01-17-2012, 11:11 PM
  2. size of dynamic array
    By dayalsoap in forum C Programming
    Replies: 3
    Last Post: 10-05-2010, 08:54 PM
  3. Dynamic Array Size?
    By Junior89 in forum C++ Programming
    Replies: 4
    Last Post: 04-04-2007, 11:31 PM
  4. size of dynamic array
    By tommy_gunn in forum C Programming
    Replies: 3
    Last Post: 12-30-2004, 08:01 PM
  5. Dynamic Array Size
    By minignaz in forum C Programming
    Replies: 11
    Last Post: 12-12-2003, 06:05 PM

Tags for this Thread