在c中通过字母顺序排序2d字符串数组

时间:2015-04-20 15:33:00

标签: c sorting multidimensional-array c-strings

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

#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]);
    }


}

1 个答案:

答案 0 :(得分:2)

您的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]覆盖applicants[i + 1],然后写入applicants[i + 1] temp中存储的上一个值,这不是applicants[i]必须if (c > 0) { strcpy(temp, applicants[i]); strcpy(applicants[i], applicants[i + 1]); strcpy(applicants[i + 1], temp); }

您需要添加大括号

{{1}}