c - 为什么这个程序会导致无限循环输出?

标签 c infinite-loop stdio

<分区>

此代码是来自日常编程邮件列表的练习。我正在尝试以相反的顺序打印出给定单词的列表。单词由空格分隔。运行下面的代码时,它会进入一个无限循环,只打印(新的)第一个单词。我已经查看了条件,对我来说一切都很好。我认为指出一个简单的错误可能需要一双新的眼睛,但我找不到任何东西。感谢任何可以伸出援手的人。

*注意:我计划在解决这个问题后将空格添加回输出。我知道到目前为止输出只是一个没有空格的长字符串。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (void)
{
    char *words;
    words = "here world hello spam foo bar baz";
    int space_indices[10];
    int counter = 0;

    // Find the spaces and keep track of the index numbers in the space_indices array
    for (int i = 0; i < strlen(words); i++) {
        if (words[i] == ' ') {
            space_indices[counter] = i;
            counter++;
        }
    }

    for (int i = counter - 1; i >= 0; i--) {
        if ( i = counter - 1) {
            // Print the first word
            for (int j = space_indices[i] + 1; j < strlen(words); j++) {
                printf("%c", words[j]);
            }
        } else if (i >= 0) {
            // Print the other words except for the last
            for (int j = space_indices[i] + 1; j < space_indices[i + 1]; j++) {
                printf("%c", words[j]);
            }
        } else {
            // Print the last word
            for (int j = 0; j < space_indices[0]; j++) {
                printf("%c", words[j]);
            }
        }
    }
}

最佳答案

正如 Havenard 所解释的,问题在于我没有使用比较运算,而是使用了赋值运算符。

这个:

if ( i = counter - 1)

应该是:

if ( i == counter - 1)

关于c - 为什么这个程序会导致无限循环输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58403272/

相关文章:

c - 如何在节点中插入字符串(由用户输入)? (二叉搜索树)

java - 无限循环或提前终止 do while 循环

c++ - 'printf' 与 C++ 中的 'cout'

在链表中创建数据类型为 "struct"的新节点

c - 结果不一致 (C)?

assembly - 不延迟汇编的循环会使我的电脑崩溃吗?

c - 为什么这个循环会无限重复?

c - 如果 '&' 没有放在 'scanf' 语句中会发生什么?

c - Arduino:printf/fprintf 打印问号而不是 float

c - 使用 While 循环完成下面的等式