Search code examples
cinfinite-loopstdio

Why does this program result in an infinite loop output?


This code is an exercise from a daily programming mailing list. I am trying to print out a list of given words in reverse order. The words are delimited by spaces. When running the code below, it enters into an infinite loop just printing the (new) first word. I have looked through the conditions and everything looks OK to me. I think it may take a fresh set of eyes to point out a simple mistake, but I can't find anything. Thanks to anyone who can lend a hand.

*Note: I am planning on adding back in the spaces to the output after this is figured out. I am aware the output will just be one long string without spaces so far.

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

Solution

  • As Havenard explained, the problem was that I was not using a comparison operation, I was using an assignment operator.

    This:

    if ( i = counter - 1)
    

    should be:

    if ( i == counter - 1)