I wrote a code to reverse a string, but the strlen
function is giving me the wrong length of string, that's why the reversing of the string is not done properly. Here is the code I wrote:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void reversestring(char string[], int start, int end);
int main() {
char str[500];
int n;
n = strlen(str);
reversestring(str, 0, n - 1);
printf("%d\n", n);
printf("The reverse string is %s", str);
return 0;
}
void reversestring(char string[], int start, int end) {
printf("enter the string:\n");
scanf("%s", string);
int temp;
while (start < end) {
//printf("insidewhile\n");
temp = string[start];
string[start] = string[end];
string[end] = temp;
start++;
end --;
}
}
strlen()
can´t give you the length of a string, when its argument does not point to a valid string, which is the case on your example:
char str[500];
int n;
n = strlen(str);
str
isn´t initialized with a string.
Providing a pointer to a char
array which doesn´t contain a string as argument to strlen()
causes undefined behavior.
Also strlen()
doesn´t return an int
. It´s return value is of type size_t
.
Also use fgets()
instead of scanf()
when input a string. It is a little bit more safe.
Solution:
Let the string get entered in main()
into str
, then use strlen()
and thereafter call the reversestring()
function:
char str[500];
size_t n;
printf("enter the string:\n");
fgets(str,500,stdin);
n = strlen(str);
reversestring(str, 0, n-1);
I also edited the function declaration and the printf()
accordingly to take care of the size_t
type.
Here is the full code (Online Example):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void reversestring(char string[], size_t start, size_t end);
int main()
{
char str[500];
size_t n;
printf("enter the string:\n");
fgets(str,500,stdin);
str[strcspn(str, "\n")] = 0; // removing trailing newline from fgets
n = strlen(str);
reversestring(str, 0, n-1);
printf("%zu\n", n);
printf("The reverse string is %s", str);
return 0;
}
void reversestring(char string[], size_t start, size_t end)
{
int temp;
while(start < end)
{ //printf("insidewhile\n");
temp = string[start];
string[start] = string[end];
string[end] = temp;
start++;
end --;
}
}
Output:
enter the string:
helloworld
10
The reverse string is dlrowolleh