-3

Beginner programmer here. I'm trying to take an input from user, reverse it and show the result. For some reason, it's printing blanks instead of the reversed string. I know that array[i] has the right information because if I use this loop on line for (int i=0; i<count; i++), it's printing the right characters. It's just not printing in reverse. What am I not getting here?

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

int main(void)
{
    printf("Please enter a word: ");
    char *word = get_string();

    int count = strlen(word);

    char array[count];

    for (int i=0; i< count; i++)
    {
        array[i] = word[i];
    }

    for (int i=count-1; i==0; i--)
    {
        printf("%c ", array[i]);
    }
    printf("\n");
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
ahmed_imtiaz
  • 143
  • 1
  • 1
  • 7

2 Answers2

1
for (int i=0; i< count; i++)
{
    array[i] = word[i];
}

You go over the string and copy it, you do not reverse it.

There is also a subtle bug in-waiting in your declaration of array, since you do not leave space for the '\0' character terminator. Passing your buffer to printf as a C-string, as opposed to character by character will have undefined behavior.

So to fix those two particular errors:

char array[count + 1];
array[count] = '\0';

for (int i = 0; i< count; i++)
{
    array[i] = word[count - i];
}

As a side note, it may not mean much to use a VLA for this small exercise, but for larger inputs it could very well overflow the call stack. Beware.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
0
// the header where strlen is
#include <string.h>

/**
 * \brief reverse the string pointed by str
**/
void reverseString(char* str) {
    int len = strlen(str);
    // the pointer for the left and right character
    char* pl = str;
    char* pr = str+len-1;
    // iterate to the middle of the string from left and right (len>>1 == len/2)
    for(int i = len>>1; i; --i, ++pl, --pr) {
        // swap the left and right character
        char l = *pl;
        *pl = *pr;
        *pr = l;
    };
};

And just call the function:

int main(void) {
    printf("Please enter a word: ");
    char *word = get_string();

    // Just call the function. Note: the memory is changed, if you want to have the original and the reversed just use a buffer and copy it with srcpy before the call
    reverseString(word)
    printf("%s\n", word);
};

And just change

char array[count];

for (int i=0; i< count; i++)
{
    array[i] = word[i];
}

to

// add an other byte for the null-terminating character!!!
char array[count+1];
strcpy(array, word);
cmdLP
  • 1,658
  • 9
  • 19