Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are a few issues with your program. The realloc() statement is not used correctly. I also prefer fgets() for getting a line. Here is my solution. This also uses realloc() to increase the allocation of the buffer lines so that you neither have to know the number of lines in advance nor do you have to read the file in two passes (faster that way). This is a common technique to use when you don't know how much memory you'll have to allocate in advance.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int main(void) { int lines_allocated = 128; int max_line_len = 100; /* Allocate lines of text */ char **words = (char **)malloc(sizeof(char*)*lines_allocated); if (words==NULL) { fprintf(stderr,"Out of memory (1).\n"); exit(1); } FILE *fp = fopen("coll.txt", "r"); if (fp == NULL) { fprintf(stderr,"Error opening file.\n"); exit(2); } int i; for (i=0;1;i++) { int j; /* Have we gone over our line allocation? */ if (i &gt;= lines_allocated) { int new_size; /* Double our allocation and re-allocate */ new_size = lines_allocated*2; words = (char **)realloc(words,sizeof(char*)*new_size); if (words==NULL) { fprintf(stderr,"Out of memory.\n"); exit(3); } lines_allocated = new_size; } /* Allocate space for the next line */ words[i] = malloc(max_line_len); if (words[i]==NULL) { fprintf(stderr,"Out of memory (3).\n"); exit(4); } if (fgets(words[i],max_line_len-1,fp)==NULL) break; /* Get rid of CR or LF at end of line */ for (j=strlen(words[i])-1;j&gt;=0 &amp;&amp; (words[i][j]=='\n' || words[i][j]=='\r');j--) ; words[i][j+1]='\0'; } /* Close file */ fclose(fp); int j; for(j = 0; j &lt; i; j++) printf("%s\n", words[j]); /* Good practice to free memory */ for (;i&gt;=0;i--) free(words[i]); free(words); return 0; } </code></pre>
    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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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