Note that there are some explanatory texts on larger screens.

plurals
  1. POrealloc homework help
    text
    copied!<p>For an assignment, part of what I have to do involves the use of <code>malloc</code> and <code>realloc</code>. I first create a 2D array of chars, the dimensions being the number of lines and the number of characters. I then use <code>malloc</code> to allocate enough memory to store input from some file. Using <code>fgets</code> I read one line in at a time, and store it in the array. This part works fine (or so I think). The problem comes in when I try to reallocate memory for more lines if need be. The program flow is supposed to be like this:</p> <p>Create a character array of 50 lines, with 80 characters per line (working)</p> <p>Use <code>fgets</code> to read one line at a time and save it to the array (working)</p> <p>When 50 lines have been read, reallocate the array to allow for 100 lines (not working)</p> <p>Keep reallocating as need be (not working)</p> <p>This is what I have so far (the core of it at least, I omitted irrelevant code):</p> <pre><code>#define NUMBER_OF_LINES 50 #define CHARACTERS_PER_LINE 80 FILE *inputFile = fopen("some.text", "r"); char **lines; lines = malloc(NUMBER_OF_LINES * sizeof(*lines)); int i; for (i = 0; i &lt; NUMBER_OF_LINES; i++) *(lines+i) = malloc(CHARACTERS_PER_LINE * sizeof(char)); int linesRemaining = NUMBER_OF_LINES; int reallocCount = 1; i = 0; while (!feof(inputFile)) { if (!linesRemaining) { reallocCount++; lines = realloc(lines, (NUM_OF_LINES * reallocCount) * sizeof(*lines)); linesRemaining = NUM_OF_LINES; } fgets(*(lines+i), CHARS_PER_LINE, inputFile); i++; linesRemaining--; } </code></pre> <p>My gut tells me the problem is with the <code>realloc</code>, so I'll explain what I <em>think</em> it's doing.</p> <pre><code>realloc(lines, (NUM_OF_LINES * reallocCount) * sizeof(*lines)); </code></pre> <p>The first argument, <code>lines</code>, is the pointer I would like to reallocate a certain amount of memory. <code>NUM_OF_LINES</code> is the amount I would like to increase the size by. I multiply this by <code>reallocLinesCount</code>, which is a counter that keeps track of how many sets of 50 lines I ought to have. The <code>sizeof(*lines)</code> part is the size of a pointer to a <code>char</code>.</p> <p>Thank you for reading and any help is greatly appreciated :)</p> <p>EDIT: thank you all for the responses; I do not have time right now to read all of the answers right now, but all of your answers will be more thoroughly read and understood once this imminent deadline has passed :D</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload