C中反转字符串的函数 [英] Function to reverse string in C

查看:64
本文介绍了C中反转字符串的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了这个函数来反转 C 中的字符串,但是在字符串中切换字符时程序崩溃了.我不知道是什么原因造成的,因此我们将不胜感激.

I wrote this function to reverse a string in C, but when switching characters in the string the program crashes. 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");
}

推荐答案

阅读本文了解更多信息 char s[] 和 char *s 有什么区别?

read this for more information What is the difference between char s[] and char *s?

另一个链接 https://stackoverflow.com/questions/22057622/whats-the-difference-structurally-between-char-and-char-string#22057685

这应该可以解决它.

main()
{    
char array[] = "Example";
reverse(array); 
}

当你执行 reverse("Example") 时,这与

char *string = "Example";
reverse(string) //wont work

这些链接应该可以从这里澄清您的疑虑.

The links should clarify your doubts from here.

这篇关于C中反转字符串的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆