在C中排列单词字典顺序

时间:2016-05-06 18:54:07

标签: 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: %s\nLast 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);
}

1 个答案:

答案 0 :(得分:0)

这是一些警告和错误。

$ 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解决了段错误并调整了循环计数器,这样你就不会超出界限。

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: %s\nLast word:  %s\n", 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