Thread: Allocating an array of unknown size?

  1. #1
    Registered User
    Join Date
    Sep 2008

    Allocating an array of unknown size?

    When inputing information from stdin, I dont know how many lines I will input, and I will not know how many spots I need to allocate in my array.

    As I read in information, I store it in my array, but how do I malloc space for it, If i dont know how big it needs to be?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    Consider using a linked list then. Each new line is added to the end of the list.

    When you reach the end of input, you'll know how many lines you have, and it's easy to allocate an array of char** to point to all the lines stored in your list.
    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
    Sep 2008
    Toronto, Canada
    Start by allocating some sized chunk... 1 meg or two. You'd probably need to allocate for an array of indexes to point to the beginnings of each string in there as well. Perhaps 100 of those. Fill them in as input comes along, keeping careful track as to capacity. If you are going to exceed the bounds, use realloc() to grab a bigger chunk.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Have problems with copying my array!
    By AvaGodess in forum C Programming
    Replies: 11
    Last Post: 09-25-2008, 12:56 AM
  2. Replies: 16
    Last Post: 11-23-2007, 01:48 PM
  3. How To Declare and Dynamically Size a Global 2D Array?
    By groberts1980 in forum C Programming
    Replies: 26
    Last Post: 11-15-2006, 09:07 AM
  4. Array size
    By tigrfire in forum C Programming
    Replies: 5
    Last Post: 11-14-2005, 08:45 PM
  5. Replies: 1
    Last Post: 09-10-2005, 06:02 AM