Home>

Enter the file name (up to 20 characters) of the data file that stores the number and test score from the keyboard, and sort by the basic exchange method.
Data file example
1001 96
1002 60
1003 87
..
..
..

The program itself works, but I want to sort only the input records, but I can't think of a method.
(I want to sort only the entered records and not to sort the uninput areas)
This program cannot handle more than 100 data, so I want to be able to handle it.

Corresponding source code
#include<stdio.h>
#include<stdlib.h>
int main (void)
{
    int n = 0, cnt = 0, flg, j, i;
    char filename [21];
    FILE * fp;
    struct seisekiA {
        int bango, tokuten;
    };struct seisekiA seiseki [100], work;
    printf ("Please enter the file name \ n");
    scanf ("% s", filename);
    if ((fp = fopen (filename, "r")) == NULL)
    {
        printf ("FILE OPEN ERROR \ n");
        exit (1);
    }
    printf ("number score \ n");
    while (fscanf (fp, "% d% d",&seiseki [n] .bango,&seiseki [n] .tokuten)! = EOF)
    {
        printf ("% 4d% 4d \ n", seiseki [n] .bango, seiseki [n] .tokuten);
        n ++;
    }
    printf ("Number of records =% d \ n", n);
    printf ("Alignment result \ n");
    flg = 0;
    while (flg == 0)
    {
        flg = 1;
        for (i = 0;i<n-1;i ++)
        {
            cnt ++;
            if (seiseki [i] .tokuten<seiseki [i + 1] .tokuten)
            {
                work = seiseki [i];
                seiseki [i] = seiseki [i + 1];
                seiseki [i + 1] = work;
                flg = 0;
            }
        }
    }
    fclose (fp);
    for (j = 0;j<n;j ++)
    {
        printf ("% 4d% 4d \ n", seiseki [j] .bango, seiseki [j] .tokuten);
    }
    printf ("number of exchanges =% d \ n", cnt);
}
What I tried

I tried to change the part of seiseki [100] on the 10th line to [n], but it became a core dump.

Supplementary information (FW/tool version, etc.)

Ubuntu 18.04.4TLS gcc 7.5.0

  • Answer # 1

    I want to prevent uninput areas from being aligned

    Isn't that the case from the beginning? In the alignment processseiseki [n-1]Only up to, so the rest remains the same.

  • Answer # 2

    If you want to support more than 100 data, check out dynamic memory allocation (per malloc, realloc, free).