Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Your key problem is that <strong><em>line</strong> pointer value does not propagate out of the <strong>getLine()</strong> function.</em> The solution is to pass <em>pointer to the <strong>line</strong> pointer</em> to the function as a parameter instead - calling it like <code>getLine(&amp;line);</code> while the function would be defined as taking parameter <code>char **line</code>. In the function, on all places where you now work with <strong>line</strong>, you would work with <strong>*line</strong> instead, i.e. dereferencing the pointer to a pointer and working with the value of the variable in <strong>main()</strong> where the pointer leads. Hope this is not too confusing. :-) Try to draw it on a piece of paper.</p> <p>(A tricky part - you must change <code>line[counter]</code> to <code>(*line)[counter]</code> because you <em>first</em> need to dereference the pointer to the string, and only <em>then</em> to access a specific character in the string.)</p> <p>There is a couple of other problems with your code:</p> <ul> <li>You use <strong>char</strong> as the type for <strong>charRead</strong>. However, the <strong>EOF</strong> constant cannot be represented using <strong>char</strong>, you need to use <strong>int</strong> - both as the type of <strong>charRead</strong> and return value of <strong>getLine()</strong>, so that you can actually distringuish between a newline and end of file.</li> <li>You forgot to return the last char read from your <strong>getLine()</strong> function. :-)</li> <li>You are reallocating the buffer after each character addition. This is not terribly efficient and therefore is a rather ugly programming practice. It is not too difficult to use another variable to track the amount of space allocated and then (i) start with allocating a reasonable chunk of memory, e.g. 64 bytes, so that ideally you will never reallocate (ii) enlarge the allocation only if you need to based on comparing the counter and your allocation size tracker. Two reallocation strategies are common - either doubling the size of the allocation or increasing the allocation by a fixed step.</li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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