//Program to get reverse of entered string.
#include<stdio.h>
#include<string.h>
void rev(char *a, char *b);
int main()
{
char a[50];
char b[50];
printf("Enter String: ");
gets(a);
printf("\n");
rev(a, b);
return 0;
}
void rev(char *a, char *b)
{
int i;
int n = strlen(a) - 1;
printf("Lenght of string : %d\n", n);
printf("\n");
for(i=0; i<n; i++)
{
b[i] = a[n];
n--;
}
b[i] = '\0';
printf("Reverse : %s", b);
}
Asked
Active
Viewed 47 times
-3

ForceBru
- 43,482
- 10
- 63
- 98

Harshraj Vaghela
- 3
- 1
-
3What is there to explain? what do you not understand? also read [Why is the gets function so dangerous](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) – Tony Tannous Sep 30 '20 at 18:49
-
The first thing that is wrong with this program is [gets](https://en.cppreference.com/w/c/io/gets). It's fatal so it doesn't really matter what happens past this point. – n. m. could be an AI Sep 30 '20 at 18:52
1 Answers
-1
Here is a correct version of that code, I have added some comments to make the changes clear
// Program to get reverse of entered string.
#include <stdio.h>
#include <string.h>
void rev(char *a, char *b);
int main() {
char a[50];
char b[50];
printf("Enter String: ");
// gets() should be fgets(), cause gets() is dangerous and even deprecated
fgets(a, sizeof a, stdin);
printf("\n");
rev(a, b);
return 0;
}
void rev(char *a, char *b) {
int i;
int n = strlen(a) - 1;
printf("Length of string : %d\n", n);
printf("\n");
// you should subtract `i` from `n` instead of decrementing `n` cause the loop depends on it
for(i = 0; i <= n; i++) {
b[i] = a[n - i];
}
b[i] = '\0';
printf("Reverse : %s", b);
}

Saadi Toumi Fouad
- 2,779
- 2
- 5
- 18