Yahoo Answers is shutting down on 4 May 2021 (Eastern Time) and the Yahoo Answers website is now in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Which would better programming?

I have a program that sorts a text file with n amount of lines using arrays. The question is: Should I search through the file to see how big the array should be, or make an array with an undefined amount of space then adjust the space after placing the values in?

Update:

Aren't dynamic variables just variables with an unknown size till runtime? I don't see how that helps. The main issue is the array in regards to handling memory use.

3 Answers

Relevance
  • ??????
    Lv 7
    8 years ago
    Favourite answer

    You could look at the filesize and make an estimate upperbound.

    A line always has CR + LF (carriage return = ASCII char nr 13, and line feed = ASCII char nr 10).

    So each line has 2 characters + the characters to store the amount.

    You could also count the number of lines first, like you suggest, but then you have to read over the file twice.

    Finally, you can use dynamic array's and adjust the allocated space when it is full. This is the fastest and neatest method i think because memory allocations are much faster than disk accesses.

    You can allocate memory dynamically in a dynamic array.

    This means that you begin with 100 places example given.

    memplaces = 100;

    mem = malloc(memplaces);

    And when it is full, you double the amount of memspace e.g. :

    memplaces *= 2;

    mem = malloc(memplaces)

    The final size is unknown till runtime of course, but you keep track of the number of items and everytime it exceeds memplaces you double the memory allocation.

    There exists even a special command realloc in C to adjust the memory size and keep the data already stored.

    Hope this helps.

  • 8 years ago

    Just make a dynamic data structure. That's probably faster than reading the entire file twice, because the hard drive is slow to access.

    There are many techniques for creating dynamic data structures. You can use a linked list, or a binary tree, or just an array that you keep reallocating when you need it to get bigger, or any of a variety of more complex data structures. Different ones may have different advantages in terms of space and time requirements.

  • 8 years ago

    You can create dynamic variables. Put the data in an 80 line array (the traditional length of a line is up to 80 characters) and create a new one for each line until the file ends.

Still have questions? Get answers by asking now.