Advertisement

01.04.2006 at 01:43PM PST, ID: 21684169
[x]
Attachment Details

Dynamic allocation of two-dimensional array

Asked by jimdgar in C Programming Language

Tags: array, dynamic, dimensional, allocation, two

Hi,

I have a (C) program which reads a stream of characters from a file into an array of data, currently structured as
     char data[num][len];
where num is relatively small (< 100) and len relatively large (up to 20000). Both num and len can vary from file to file. I want to optimize the code using dynamic memory allocation. The data in the file is formatted something like:
...
data[0] header
   len_1 of chars
data[1] header
   len_2 of chars
...
data[n] header
   len_n of chars

Making dynamically allocated structures for each 'num' is easy, but I don't know how long each 'len' is until it is read. One obvious implementation is to use malloc to create the 1st char of data[0] and then realloc for each additional char, but this seems inefficient and potentially slow to me.

The other solution may be to malloc a block (1000?) of chars, read until it's full, realloc another block if needed, and so on, then free any leftover space in the last block at the end. Is this approach efficient or does someone have a better recommendation?

jimdgar
Start Free Trial
 
 
Loading Advertisement...
 
[+][-]01.04.2006 at 02:01PM PST, ID: 15612213

View this solution now by starting your 7-day free trial. Setting up your free trial is quick, easy, and secure. We will return you to this solution, unlocked, when you're done.

 

About this solution

Zone: C Programming Language
Tags: array, dynamic, dimensional, allocation, two
Sign Up Now!
Solution Provided By: grg99
Participating Experts: 2
Solution Grade: A
 
 
[+][-]01.04.2006 at 02:03PM PST, ID: 15612225

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 7-day free trial to view this Expert Comment or ask the Experts your question.

 
 
Loading Advertisement...
20080716-EE-VQP-32