Understanding C Language String Sorting

Asked 1 years ago, Updated 1 years ago, 331 views

In C language, enter ASC in ascending order
I'm trying to create a descending program after entering DESC, but could someone please tell me the wrong part because the descending order doesn't work better?

#include<stdio.h>
# include <string.h>

void swap(char*a,char*b){
    chat[10];
    strcpy(t,a);
    strcpy(a,b);
    strcpy(b,t);
}

void sort(chars[][6], intn, intf){
    inti,j,t;
    if(f==0){
        for(i=1;i<n;i++){
            for(j=1;j<n;j++){
                if(strcmp(s[j-1], s[j])>0){
                    strcpy(t,s[j-1]);
                    strcpy(s[j-1], s[j]);
                    strcpy(s[j],t);
                }
            }
        }
    }
    else{
            for(i=1;i<n;i++){
                for(j=1;j<n;j++){
                    if(strcmp(s[j-1], s[j])<0){
                        strcpy(t,s[j-1]);
                        strcpy(s[j-1], s[j]);
                        strcpy(s[j],t);
                    }
                }
            }
    }
}

void main()
{
    inti,n;
    char sin[9][6];
    charcom[16];
    FILE*fp;

    fp = fopen("before_sort2.txt", "r");

    if(fp==NULL){
        printf("File Open Failed\n";
        return-1;
    }

    for(i=0;i<9;i++){
        fscanf(fp, "%s", &(sin[i])));
    }
    fclose(fp);

    printf("command>");
    scanf("%s",com);
    if(strcmp(com, "ASC")==0){
        sort(sin,9,0);
    }
    else if(strcmp(com, "DESC")==0){
        sort(sin,9,1);
    }

    for(i=0;i<9;i++){
        printf("%s\n", sin[i]);
    }
}

c

2022-11-11 06:48

2 Answers

When you build on VC++, you receive the following errors and warnings:(The format has been changed)
Rather than whether the descending order can be processed or not, the first ascending order processing was not complete.

 line type contents
17 Error Local variable 't' not initialized is used
17 Warning 'function': Indirect reference level is different between 'char*' and 'int'.
17 Warning 'strcpy': The type of is different from the temporary and real arguments of 1.
19 Warning 'function': Indirect reference level is different between 'char*' and 'int'.
19 Warning 'strcpy': The type of is different from the temporary and real arguments of 2.
       Lines 28 and 30 are the same warnings as lines 17 and 19 respectively (no errors are displayed but the content is the same)
39 Warning 'n': The local variable has never been used.
48 Warning 'main': A function with a return type declared as 'void' returned a value.


2022-11-11 07:54

The auto variable t in the sort function is invalid.
Is it because it is a school challenge not to use the qsort standard function?


2022-11-11 08:07

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.