[英]Function to reverse string in C
I wrote this function to reverse a string in C, but when switching characters in the string the program crashes. 我编写了此函数以反转C中的字符串,但是当切换字符串中的字符时,程序崩溃。 I have no idea what's causing it, so any help would be appreciated.
我不知道是什么原因造成的,所以我们将不胜感激。
void reverse(char s[])
{
char c;
int i;
int j;
for (i = 0, j = (strlen(s) - 1); i < j; i++, j--)
{
c = s[i];
s[i] = s[j]; //An error occurs here
s[j] = c;
}
printf("%s", s);
}
main()
{
reverse("Example");
}
read this for more information What is the difference between char s[] and char *s? 阅读此以获得更多信息char s []和char * s有什么区别?
Another link https://stackoverflow.com/questions/22057622/whats-the-difference-structurally-between-char-and-char-string#22057685 另一个链接https://stackoverflow.com/questions/22057622/whats-the-difference-structurally-between-char-and-char-string#22057685
this should fix it. 这应该解决它。
main()
{
char array[] = "Example";
reverse(array);
}
when you do reverse("Example")
this is the same as 当您进行
reverse("Example")
这与
char *string = "Example";
reverse(string) //wont work
The links should clarify your doubts from here. 链接应从此处阐明您的疑问。
"Example"
is a string literal, which usually means you cannot change it. "Example"
是字符串文字,通常意味着您无法更改它。
Please try this: 请尝试以下方法:
char str[] = "Example";
reverse(str);
This should work: 这应该工作:
#include<string.h>
int main()
{
char str[100], temp = 0;
int i = 0, j = 0;
printf("nEnter the string :");
gets(str);
i = 0;
j = strlen(str)-1;
while(i<j)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
i++;
j--;
}
printf("nReverse string is :%s",str);
return(0);
}
You need to take character pointer as a parameter in your function: 您需要将字符指针作为函数中的参数:
Void reverse (char *ptr)
{
// ...
}
And perform operation on pointer. 并在指针上执行操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.