I am trying to create a bubble sorter that takes a 2D array from a file with full names and sorts them in alphabetical order. The problem is that when the bubble sorter function is called, the program stops and stays like that indefinitely.
this is the code:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
void sortStrings(char[100][30], int);
int main()
{
FILE* fp;
char name[100][30];
int list, n;
n = 100;
fp = fopen("List.txt", "r");
if (fp == 0)
{
printf("Cannot open file");
}
else
{
list = 0;
while (!feof(fp)) //end of file
{
fgets(name[list], 30, fp);
list++;
}
}
sortStrings(name, n);
printf("Strings in sorted order are : ");
for (int i = 0; i < n; i++)
printf("\n String %d is %s", i + 1, name[i]);
return 0;
}
void sortStrings(char name[100][30], int n)
{
char temp[100];
int i, j;
// Sorting strings using bubble sort
for (i = 1; i <= n; i++)
for (j = 0; j <= n - i; j++)
if (strcmp(name[j], name[j + 1]) > 0)
{
strcpy(temp, name[j]);
strcpy(name[j], name[j + 1]);
strcpy(name[j + 1], temp);
}
}
also, this error shows up in the visual studio
Exception thrown at 0x6A9DF791 (ucrtbased.dll) in name organizer.exe: 0xC0000005: Access violation reading location 0xCCCCCE16.