0

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.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
GHG HGH
  • 37
  • 3
  • https://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong – Barmar Oct 20 '21 at 20:29
  • So what if `list` reaches `100`? – CherryDT Oct 20 '21 at 20:30
  • 1
    Array indexes start at 0 and go to `n-1`. `for (i = 1; i <= n; i++)` is wrong. – Barmar Oct 20 '21 at 20:31
  • 1
    `sortStrings(name, n);` should be `sortStrings(name, list);`. As it is you are trying to read uninitialized data from `name`. Same with the last `for` loop in `main`. – kaylum Oct 20 '21 at 20:31
  • @Barmar I initially thought so too but the code doesn't directly use `i` as an index. It's still probably wrong but more in the `j+1` index. – kaylum Oct 20 '21 at 20:35

0 Answers0