如何扭转代替字符串中c。使用指针? [英] How to reverse a string in place in c using pointers?

查看:117
本文介绍了如何扭转代替字符串中c。使用指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  你如何扭转地方的字符串在C或C ++?


好吧,我正在学习C,我试图扭转使用指针代替字符串。 (我知道你可以使用一个数组,这更多的是学习指针。)

我一直试图运行下面的code时得到段错误。海湾合作委员会似乎不喜欢 *年底= *开头; 行。这是为什么?

特别是因为我的code是几乎相同的已经讨论上为非作恶çFN

 
#包括LT&;文件stdio.h>
#包括LT&; string.h中>无效my_strrev(字符*开头){
    焦温度;
    字符*结束;
    最终= +开始的strlen(开始)-1;    而(END>开始){
        TEMP = *结束;
        *结束= *开始;
        *开始=温度;
        结束 - ;
        开始++;
    }
}主要(){
    字符*字符串=foobar的;
    my_strrev(字符串);
    的printf(%S,字符串);
}


解决方案

的一个问题在于,你传递给函数参数:

 的char *字符串=foobar的;

这是在只读部分分配的静态字符串。当你试图用覆盖它。

  *年底= *开始;

您会得到段错误。

与尝试

 字符字符串[] =foobar的;

和你应该注意到的差异。

的关键点是,在第一种情况下的串中的只读区段存在,并同时在第二壳体字符的具有适当大小的阵列栈和静态上保留用于只是一个指向它的指针字符串(总是存在)复制到它。之后,你可以自由地修改数组的内容。

Possible Duplicate:
How do you reverse a string in place in C or C++?

Ok, I'm learning C, and I'm trying to reverse a string in place using pointers. (I know you can use an array, this is more about learning about pointers.)

I keep getting segfaults when trying to run the code below. Gcc seems not to like the *end = *begin; line. Why is that?

especially since my code is nearly identical to the non-evil c fn already discussed


#include <stdio.h>
#include <string.h>

void my_strrev(char* begin){
    char temp;
    char* end;
    end = begin + strlen(begin)-1;

    while(end>begin){
        temp = *end;
        *end = *begin;
        *begin = temp;
        end--;
        begin++;
    } 
}

main(){
    char *string = "foobar";
    my_strrev(string);
    printf("%s", string);
}

解决方案

One problem lies with the parameter you pass to the function:

char *string = "foobar";

This is a static string allocated in the read-only portion. When you try to overwrite it with

*end = *begin;

you'll get the segfault.

Try with

char string[] = "foobar";

and you should notice a difference.

The key point is that in the first case the string exists in the read-only segment and just a pointer to it is used while in the second case an array of chars with the proper size is reserved on the stack and the static string (which always exists) is copied into it. After that you're free to modify the content of the array.

这篇关于如何扭转代替字符串中c。使用指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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