I wrote this code but cannot figure out the issues that arise when trying to compile.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int find_First_Letter (char **word_Array, int num_words); /*Function to find the first letter of a string*/
int main (void){
FILE *in, *out;
int num_words, num_letters, x, y;
in = fopen("alphabetic_sort.dat", "r");
out = fopen("alphabetic_sort.out", "w");
if (in == NULL || out == NULL) /*Check to see whether files can be openned or not*/
{
printf("Error opening files!\n");
fclose(in);
fclose(out);
return -1;
}
char **wordArray, c = '\0';
fscanf(in, "%d", &num_words);
wordArray = (char*) malloc(num_words*sizeof(char)); /*Creates memory for every word*/
for(x = 0; x<num_words; x++){
fscanf(in, "%d ", &num_letters);
(wordArray + x) = (char) malloc((num_letters + 1)*sizeof(char)); /*Creates memory for every letter in the word. +1 due to null character at the end*/
for (y = 0; y < num_letters; y++)
{
while (!((c >= 'a' && c <= 'z') || c == '\n'))
{
fscanf(in, "%c", &c);
}
if (c == '\n')
{
((wordArray + x) + y) = '\0'; /*Sets newline to a null character*/
}else{
((wordArray + x) + y) = c;
}
c = '\0'; /*c is set to a null character*/
}
}
int word_index;
char *sortedwordArray = (char) malloc(num_words * sizeof(char)); /*Memoery is allocated according to the number of words inputted*/
for (x = 0; x < num_words; x++)
{
word_index = find_First_Letter(wordArray, num_words);
sortedwordArray[x] = wordArray[word_index];
wordArray[word_index] = NULL
}
for (x = 0; x < num_words; x++)
{
fprintf(out, "%s\n", sortedwordArray[x]); /*Output gets printed to the required file*/
}
for (x = 0; x < num_words; x++)
{
free(*(wordArray + x)); /*Frees the memory preventing memory leaks*/
}
fclose(in); /*Closes input file*/
fclose(out); /*Closes output file*/
return 0;
}
int find_First_Letter (char **word_Array, int num_words){
int i, word_index;
char *First_Word;
word_index = 0;
for (i = 0; i < num_words; i++) /*Find the first non-null pointer*/
{
if (word_Array[i] != NULL )
{
First_Word = word_Array[i];
word_index = i;
break;
}
}
for (i = word_index + 1; i < num_words; i++)
{
if (word_Array[i] == NULL) /*Null characters are to be ignored*/
{
continue;
}
else if (strcmp(First_Word, word_Array[i]) > 0) /*Compare two strings to find if the current word is a higher value*/
{
First_Word = word_Array[i];
word_index = i;
}
}
return word_index;
}