kashveyron kashveyron - 15 days ago 5x
C Question

Why is my array being printed incorrectly?

I have written a simple program that reverses an array. For example, the string 'hello' would be printed out as 'olleh'. However, when I input something like 'hello', it prints out half the string reversed, followed by some cryptic characters and other nonsense that shouldn't be there.

My source code is as follows:

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

int main()
char str[100], temp;
int i = 0, j = 0;

printf("Enter a string:\n");
fgets(str, 100, stdin);
// scanf("%s", &str);

j = strlen(str) - 1;
while (i < j) {
temp = str[i];
str[i] = str[j];
str[j] = str[temp];

printf("The reversed string is: %s", str);

return (0);

Some of the output I get is 'oll' then a small square with four numbers inside. This can vary, sometimes printing 'olx' or 'olH' or even 'ol' with a question mark in a diamond shape. Why is my program not working as it should? Does the array already contain some other encoded information?


Lets take a closer look at these two lines:

temp = str[i];
str[j] = str[temp];

In the first you set temp to the character in str[i]. The other you use temp as the index into str. But temp is not an index, it's a character. So the last line should be

str[j] = temp;