Allocating an array of unknown size?

This is a discussion on Allocating an array of unknown size? within the C Programming forums, part of the General Programming Boards category; When inputing information from stdin, I dont know how many lines I will input, and I will not know how ...

  1. #1
    Registered User
    Join Date
    Sep 2008
    Posts
    58

    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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,452
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,831
    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, 12: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, 08:07 AM
  4. Array size
    By tigrfire in forum C Programming
    Replies: 5
    Last Post: 11-14-2005, 07:45 PM
  5. Replies: 1
    Last Post: 09-10-2005, 06:02 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21