Note that there are some explanatory texts on larger screens.

plurals
  1. POShuffle array (seg fault)
    text
    copied!<p>So I am supposed to create a function that accomplishes: Purpose: program to shuffle the lines of a text file</p> <ul> <li>Read the file into an array</li> <li>Count lines and maximum length</li> <li>Compute maximum width for array</li> <li>Get file pointer to the beginning</li> <li>Reserve memory for a dynamic array of strings</li> <li>Read a line and store in allocated memory</li> <li>Turn the \n into \0</li> <li>Print lines from array (test)</li> <li>Shuffle array</li> <li>Print lines from array (test)</li> <li>Free memory and close file</li> </ul> <p>(just to give some background)</p> <p>However, when I go to print the shuffled array, I get segmentation faults. Occasionally, it prints one or two of the strings, but sometimes It just says "Shuffled Array" and then I get a segmentation fault. Any ideas?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;time.h&gt; // Accepts: command line input // Returns: 0 if no error int main(int argc, char *argv[] ){ int x = 0, i, lineCount = 0, maxLen = 0; char line[500], temp; FILE *file = fopen( argv[1], "r" ); // check if file exists if (file == NULL){ printf("Cannot open file\n"); return 1; } // Gets lines, max length of string while (fgets(line, sizeof(line), file) != NULL){ lineCount++; if (strlen(line) &gt; maxLen) maxLen = strlen(line); } rewind(file); char *lineArray[lineCount]; while (fgets(line, sizeof(line), file) != NULL) { lineArray[x] = malloc(strlen(line)); if (lineArray[x] == NULL){ printf("A memory error occurred.\n"); return(1); } strcpy(lineArray[x], line); // change \n to \0 lineArray[x][strlen(lineArray[x])-1] = '\0'; x++; } printf("File %s has %d lines with maximum length of %d characters\n", argv[1], lineCount, maxLen); printf("Original Array\n"); for (x = 0; x &lt; lineCount; x++) printf("%2d %s\n", x, lineArray[x]); // Shuffle array srand( (unsigned int) time(NULL)); for (x = lineCount - 1; x &gt;= 0; x--){ i = (int) rand() % lineCount; temp = lineArray[x]; lineArray[x] = lineArray[i]; lineArray[i] = temp; } printf("\nShuffled Array\n"); for (x = 0; x &lt; lineCount; x++) printf("%2d %s\n", x, lineArray[x]); // free allocated memory for (x = 0; x &lt; lineCount; x++) free(lineArray[x]); free(lineArray); fclose(file); return 0; } </code></pre>
 

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