There are multiple errors in your code. The obvious ones are that gets
is used wrong (and, to be honest, that it is used at all) and it does not output the result in any way. But let's apply some quick fixes with minimal changes to your logic:
#include <stdio.h>
#include <string.h>
void FirstReverse(char str[]) {
int a = strlen(str);
for(int i=0; i<strlen(str) ;i++){
str[i] = str[a-1];
a-=1;
}
}
int main(void) {
char string[100]; // This is going to be our working field where the changes happen
fgets(string, 100, stdin); // read a line of up to 100 characters into "string"
FirstReverse(string); // do the work (this could be chained, like it was originally)
puts(string); // output the result
return 0;
}
Now it compiles and executes without failing but the result is wrong:
In: My favourite string
Out: gnirts ette string
What went wrong? Let's follow what happens step by step:
i a
↓ ↓
My favourite string
(program writes the last character [see point 3 below] in place of `M`)
↓ ↓
y favourite string
(program writes `g` in place of `y`)
↓ ↓
g favourite string
(program writes `n` in place of the space)
↓ ↓
gnfavourite string
(program writes `i` in place of `f`)
etc.
ia
↓↓
gnirts eite string
(program writes `t` in place of `i`)
ai
↓↓
gnirts ette string
(program writes `t` in place of `t`)
a i
↓ ↓
gnirts ette string
(program writes `e` in place of `e`)
etc.
Three problems here:
By rewriting a character from the start by another from the end, you're not doing swapping. You're just copying the data from the end to start (but surely, in reverse order). The original is lost.
You are actually going twice through, because by the time i
reaches half of the interval, a
keeps decreasing and they cross. Now i
still needs to finish the loop and a
continues towards the beginning of the string where you've already been. If you actually did swapping, you'd swap 1 with 2 and then later 2 with 1 again, resulting in the original unchanged!
(minor) A string returned by (f)gets
ends with a newline character, so that becomes the beginning of your result. Probably not what you want, but has an easy fix of chopping that off before feeding the string to your function.
You'll need to deal with each of these, other answers by now contain some advice. But I thought it instructive to run your code and try to "think like the machine" in explaining why the computer misunderstands your intention. If you swap the letters by copying one in a temporary variable, then rewriting str[i]
, then writing back in str[a-1]
from the temporary, and stop before i
and a
cross each other, you can see for yourself you'll take care of 1 and 2.