Question:

C programming instructions?

by  |  earlier

0 LIKES UnLike

Hi everybody,

I'm trying to do an assignment and I can't figure out what this instruction meant.

"Use a dynamic array of "lines". By a "line", we mean a dynamically-allocated array of characters just large enough to hold the line we have read. Although each line must be dynamically-allocated(& of just the right size), you may assume that each line has fewer than BUFSIZE characters, where BUFSIZE is a macro with a value of 512."

So at this point, I understand that I will need to use fgets to get the line and store it dynamically using malloc() into an array. Then, it says...

"The dynamic array of "lines" needs to grow as more lines are read. ...we'll start (not counting 0) with a size of 1 & double the size everytime the array needs to grow. Example: 1 "line" to 2 "lines" then 4, 8, 16 & so on until all lines in the input are read."

I wasn't sure what was meant by that. I thought with malloc, you have to specifically declare the size right away like malloc(BUFSIZE)?

If anyone could shed some light on this, that would be great.

Any help is appreciated.

 Tags:

   Report

1 ANSWERS


  1. Yes, malloc requires you to pass the size of the space you're allocating. What you should do is use a buffer (in this case, an array of 512 chars) to hold the newly-read line from fgets, and then use strlen to find the length of the line that was read in. After that, you know how much space to grab with malloc.

    For the array of lines, you'll have to recopy the array contents into a newly allocated space when you enlarge it past its limit (don't forget to free the old array). Allocate space for some number of char pointers (call that number n), and then copy and extend the array every time you read another line beyond what the current array can hold.

    1) malloc space for n char*

    2) read in more lines until you've got n of them (or there are no more lines)

    3) malloc space for n*2, multiply n by 2

    4) copy the old array into the new space, and free the old array's space

    5) loop back to 2

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.