Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><code>lineArray</code> should be declared as an array of <code>char *</code> instead of a pointer to char:</p> <pre><code>char *lineArray[MAX_LINES]; </code></pre> <p>Also, consider what happens when you enter the <code>while</code> loop: your code has undefined behavior, because you are accessing <code>lineArray[x]</code>, which was never initialized, and will contain garbage values.</p> <p>You should use <code>fgets</code> instead to read a whole line into <code>line</code>, and then copy it into <code>lineArray</code>. Something like this:</p> <pre><code>while (fgets(line, sizeof(line), file) != NULL) { lineCount++; lineArray[x] = malloc(strlen(line)); strcpy(lineArray[x], line); printf("%s\n", lineArray[x]); x++; } </code></pre> <p>From your post, it appears that you don't want to be limited to <code>MAX_LINES</code>, and you want to read the whole file first to determine the array size. To do so, you can use a similar loop to count the number of lines first, like this:</p> <pre><code>while (fgets(line, sizeof(line), file) != NULL) { lineCount++; } </code></pre> <p>After this loop, <code>lineCount</code> will hold the size for <code>lineArray</code>. </p> <p>In this case, you may want to declare <code>lineArray</code> as <code>char **</code> and allocate it dynamically:</p> <pre><code>lineArray = malloc(sizeof(char *)*lineCount); </code></pre> <p>Then, get back to the beginning of the file by calling <code>rewind(file);</code> and execute the loop that copies each line into <code>lineArray</code>. In summary, your code would look something like:</p> <pre><code>while (fgets(line, sizeof(line), file) != NULL) { lineCount++; } lineArray = malloc(sizeof(char *)*lineCount); rewind(file); while (fgets(line, sizeof(line), file) != NULL) { lineArray[x] = malloc(strlen(line)); strcpy(lineArray[x], line); printf("%s\n", lineArray[x]); x++; } </code></pre> <p>Note 1: This is inefficient. File I/O is extremely slow, and you're reading it twice. Consider if this is really how you want to do it. Maybe a good approach would be to force input files to say how many lines they have.</p> <p>Note 2: You should check <code>malloc()</code>'s return value. I didn't do it in this example, but in real world, please do it.</p> <p>Note 3 : In the end, remember to <code>free()</code> every position <code>lineArray[i]</code>, and after that, free <code>lineArray</code>.</p>
    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