开发者

Something is wrong with this C code to reverse string, but I dont know what ? please help

开发者 https://www.devze.com 2023-02-04 11:18 出处:网络
I am beginnner to programming. I wrote this little program to reverse a string. But if I try to reverse a string which is less than 5 characters long then it gives wrong output. I cant seem to find wh

I am beginnner to programming. I wrote this little program to reverse a string. But if I try to reverse a string which is less than 5 characters long then it gives wrong output. I cant seem to find whats wrong.

#include<stdio.h>
#include<string.h>
int main()
{
 char test[50];
 char rtest[50];
 int i, j=0;
 printf("Enter string : ");
 scanf("%s", test); 
 int max = strlen(test) - 1;
 for ( i = max; i>=0; i--)
 {
  rtest[j开发者_如何学C] = test[i];
  j++;
 }
 printf("Reversal is : %s\n", rtest); 

 return 0;
}


You are not terminating the reversed string with a 0. (all strings in C are 0-terminated)

In this case, the printf will (likely, depending on the unitialized contents of the rtest array) create a buffer overflow.

Add a rtest[max+1]=0; after the for loop and everything should be fine. Otherwise you can declare char rtest[50] = {0} (this will initialize the whole array with 0s).


rtest is unitialized.

You should add rtest[j] = '\0'; after the for loop to say where the string ends


void reverse(char* str)
{
 int len = strlen(str);
 for (int i = 0; i < len / 2; ++i) {
  char tmp = str[i];
  str[i] = str[len - 1 - i];
  str[len - 1 - i] = tmp;
 }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号