通过在c中按字母顺序排序二维字符串数组

sorting a 2d string array by alphabetizing in c

我的循环只安排第一个元素,我尝试放置一个外部循环但它不起作用。我是否需要在我的程序中使用另一个循环或初始化另一个字符数组[] 来传输循环?

#include <stdio.h>
int main(void)
{
    char applicants[10][15],temp[15];
    char swap[10][15];
    int apps,i,j,c=0;

    printf("how many applicants?\n");
    scanf("%d",&apps);

    printf("enter the names of the applicants on seperate lines\n");
    printf("in order in which they applied for > ");
    for (i=0;i<apps;i++){
       scanf("%s",applicants[i]);
    }

    printf("\napplication order\n");
    printf("-----------------\n");
    for (i=0;i<apps;i++){
       printf("\t%s\n",applicants[i]);
    }

    for(i=0;i<apps-1;i++){
        c=strcmp(applicants[i],applicants[i+1]);
        printf("\n%d\n",c);
        if(c>0)
            strcpy(temp,applicants[i]);
            strcpy(applicants[i],applicants[i+1]);
            strcpy(applicants[i+1],temp);
    }

    printf("\n\n alphebatize order\n");
    printf("-------------------\n");
    for (i=0;i<apps;i++){
       printf("\t%s\n",applicants[i]);
    }


if(strcmp(applicants[0],applicants[1])>0){
        printf("\n\n%s is greater than %s",applicants[0],applicants[1]);
    }


}

您的 if 语句此处缺少大括号

if(c>0)
    strcpy(temp,applicants[i]);
    strcpy(applicants[i],applicants[i+1]);
    strcpy(applicants[i+1],temp);

这与

的意思相同
if (c > 0)
 {
    strcpy(temp, applicants[i]);
 }
strcpy(applicants[i], applicants[i + 1]);
strcpy(applicants[i + 1], temp);

所以你要用 applicants[i + 1] 覆盖 applicants[i],然后写入 applicants[i + 1] 存储在 temp 中的 previous 值], 这不一定是 applicants[i].

你需要加上大括号

if (c > 0)
 {
    strcpy(temp, applicants[i]);
    strcpy(applicants[i], applicants[i + 1]);
    strcpy(applicants[i + 1], temp);
 }