在C中按字典顺序排列单词



我尝试根据字典顺序对输入的单词进行排序。但它给出了错误。我想我在使用函数时做错了什么。你能告诉我怎么了吗?

void rank(char word[][100], int size)
{
    int i,j;
    char temp[100];
    for(i=0;i<size;i++)
    for(j=0;j<size;j++)
    {
        if(strcmp(word[j],word[j+1])>0)
        {
            strcpy(temp,word[j]);
            strcpy(word[j],word[j+1]);
            strcpy(word[j+1],temp);
        }
    }
    printf("First word: %snLast word:  %s",word[0],word[size-1]);
}
int main()
{
    char word[100][200];
    int i=0;
    while(strlen(word[i-1])!=4)
    {
        printf("enter word: ");
        scanf("%s",word[i]); 
        i++;
    }  
    rank(word,i);
}

这是一些警告和错误。

$ gcc main.c 
main.c: In function ‘main’:
main.c:35:10: warning: passing argument 1 of ‘rank’ from incompatible pointer type [-Wincompatible-pointer-types]
     rank(word,i);
          ^
main.c:5:6: note: expected ‘char (*)[100]’ but argument is of type ‘char (*)[200]’
 void rank(char word[][100], int size)

有些数组是越界的:while(strlen(word[i-1])!=4)一个工作示例与您的代码类似。我使用了do...while来处理segfault,并调整了循环计数器,这样就不会越界。

void rank(char word[][200], int size){
    char temp[100];
    for (int i = 0; i < size - 1; ++i) {
        for (int j = i + 1; j < size; ++j) {
            if (strcmp(word[i], word[j]) > 0) {
                strcpy(temp, word[i]);
                strcpy(word[i], word[j]);
                strcpy(word[j], temp);
            }
        }
    }
    printf("First word: %snLast word:  %sn", word[0], word[size - 1]);
}
int main() {
    char word[100][200];
    int i = 0;
    do {
        printf("enter word: ");
        scanf("%s", word[i]);
        i++;
    } while (strlen(word[i - 1]) != 4);
    rank(word,i);
    return (0);
}

测试

 $ ./a.out 
enter word: Superman
enter word: Batman
enter word: Wolverine
enter word: Cyclops
enter word: Thor
First word: Batman
Last word:  Wolverine

最新更新