I just started to learn C and need some helps. I already compiled my code and fixed all warnings that occur. However, when I run my program it says 'Segmentation Fault' and this is my code.
#include <stdio.h> #include <string.h> char *sorting(char word[51], int n) { for (int i = 0; i < n; i++) { for (int j = i+1; j < n; j++) { if (word[i] > word[j]) { char temp = word[i]; word[i] = word[j]; word[j] = temp; } } } return word; } From above, I just sort the word in order to use in strcmp.
First I will read file that contains jumbled words. Next read dictionary's file. Then I will check whether two words are the same.
int main(int argc, char **dict, char **jambles) { const char *j = jambles[1]; FILE *jambles_file = fopen(j, "r"); char jambles_words[51]; while (fgets(jambles_words, sizeof(jambles_words), jambles_file)) { int count = 0; const char *d = dict[1]; FILE *dict_file = fopen(d ,"r"); char dict_words[51]; printf("%s", jambles_words); while (fgets(dict_words, sizeof(dict_words), dict_file)) { int length_jambles = strlen(jambles_words); int length_dict = strlen(dict_words); char *j_ = jambles_words; char *d_ = dict_words; const char *sort_jambles = sorting(j_, length_jambles); const char *sort_dict = sorting(d_, length_dict); if (length_jambles == length_dict) { int compare = strcmp(sort_jambles, sort_dict); if (compare == 0) { printf("%s", dict_words); count++; } } else if (count == 0) { printf("NO MACTHES"); } } printf("\n"); } return 0; } I still don't know what are the mistakes of my code even I already search on the internet for the causes of Segmentation Fault.
%50sand always check important return values.int main(int argc, char **dict, char **jambles)????mainfunction declaration. Depending on system it might work, but not as you expect.int main()