如何使用 strcmp 对二维字符数组的行(字符串)进行排序?

How to sort rows (strings) of 2d char array using strcmp?

所以我需要对二维字符数组的行进行排序。如果用户输入:

  1. wxyz
  2. abdf
  3. abcd
  4. 我没有
  5. qrst

应该return

  1. abcd
  2. abdf
  3. 我没有
  4. qrst
  5. wxyz

    虽然我的排序方法有问题。是否可以在不使用指针的情况下进行排序,还是应该使用指针?它甚至将所有用户输入存储到 temp 中,这很奇怪,因为它的长度为 5。

       #include <stdio.h>
       #include <string.h>
       void sortStr(char str[5][4]);
    
       int main()
    {
        char str[5][4];
        int i,r,c;
    
    
    
        //user inputs 5 strings in 2d array.
    for(i=0;i<5;i++)
    {
       printf("\nEnter a string %d: ",i+1);
       scanf(" %[^\n]",&str[i]);
    }
    
    sortStr(str);
    //display array
    for(r = 0; r<5; r++)
    {
        for(c=0; c<4; c++)
        {
            printf("%c",str[r][c]);
        }
        printf("\n");
    }
    
     return 0;
      }
    
    void sortStr(char str[5][4])
    {
        int i, j;
    char temp[5];
        //this sorts each row based
        for(i=0; i<5; i++){
                printf("T1:\n");
            for(j=i+1; j<4; j++)
            {
                printf("T2:\n");
                if(strcmp(str[i],str[j]) > 0)
                {
                    //testing where code crashes
                    printf("T3:\n");
                    strcpy(temp,str[i]);
                    printf("T4:\n");
                    printf("%s\n",temp);//temp has all user input. How?
                    strcpy(str[i],str[j]);//code crashes
                    printf("T5:\n");
                    strcpy(str[j],temp);
                    printf("T6:\n");
                }
            }
        }
    }
    

像这样使用qsort

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

int main(void){
    char str[5][5];//5 for read 4 character + null-terminator
    int i;

    for(i=0;i<5;i++){
        printf("\nEnter a string %d: ", i+1);
        scanf(" %4[^\n]", str[i]);
    }

    qsort(str, 5, sizeof(*str), (int (*)(const void*, const void*))strcmp);

    puts("");
    for(i=0;i<5;i++){
        puts(str[i]);
    }

    return 0;
}