Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C语言中单词词典顺序的排序_C - Fatal编程技术网

C语言中单词词典顺序的排序

C语言中单词词典顺序的排序,c,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) {

我试着按照字典的顺序对输入的单词进行排序。但它给出了错误。我想我在使用该函数时出错了。你能告诉我怎么了吗

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);
}
void秩(字符字[][100],整数大小)
{
int i,j;
炭温度[100];

对于(i=0;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
来解决SEGFULT问题,并调整循环计数器,使您不会超出范围

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

j+1
替换为
i
j
等于
size-1
时,您正在与
word[j+1]
进行比较和交换,后者是
word[size]
超出了
word
数组的末尾。所以
j它不是这样工作的!你告诉我们哪里出了问题,我们告诉你为什么出了问题,以及如何更正它。看,我担心你的代码无法工作。检查你声明“word”的位置,它们没有一致的签名。当“word”为空时,使用strlen。如果你最初设置“I”到0,然后从中删除1,你将得到-1。你不能用它为数组编制索引。只需花点时间学习C/编程基础。这是一个冒泡排序问题。与字典无关。但它比注释的错误严重得多-看看
main
中的混乱情况。首先,使用未初始化的变量。其次,数组不是与函数所期望的相同。接下来,
word[i-1]
在第一次迭代中是未定义的行为,当
i=0
时。
 $ ./a.out 
enter word: Superman
enter word: Batman
enter word: Wolverine
enter word: Cyclops
enter word: Thor
First word: Batman
Last word:  Wolverine