C语言基础学习之指针操作字符串反转

    重新温故C语言发现好多基本的东西在大学期间没有深刻理解,导致基础太差,特别是指针,想起来觉得满可悲的,大学时虽然也努力学习了,可惜啊,深度不够,现在在linux下重学C语言,收获颇多。

    如今工作多年,重新回顾那段岁月,思海起伏,如若重新来过,我愿意终日与你为伴。

    题目:用C语言指针实现字符串的反转,比如输入“ABCD”,输出“DCBA”;

    要求:不能使用数组下标,不能使用C库函数中任何跟字符串操作相关的函数,不能声明用一个字符数组来临时存放字符串。

    代码如下:

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

void reverse_string(char *string)
{
    char temp_pch = '\0';
    char *pstr = string;
    int len=0;
    int i = 0;
    if(*string == '\0')
    {
        printf("The string is null.\n");
        
    }
    else
    {
        while(*string++ != '\0')
            len++;                             /*取字符串长度*/
        pstr = string-2;                    /*取完长度后,指针指向字符串末尾的结束字符位置,需要移动到末尾一个有效字符上。*/
        string = string-len-1;         /*指针重新移到字符串头部*/
        for(i=0; i<len/2; i++)
        {
            temp_pch = *string;
            *string = *pstr;
            *pstr = temp_pch;

            string++;                          /*字符串头尾互换,指针移动到中间即完成头尾互换*/

            pstr--;      

}

        string = string - len/2;                   /*指针从字符串中间位置移动到头部*/
        printf("The string were reversed is: %s\n", string);
    }
}

main()
{
    char orig_str[] = "Happy New Year, my dear friend!";        /*只能定义成数组,不能是指针。*/
    reverse_string(orig_str);

}


linux上编译通过。

注:main ()中 orig_str定义的时候不能定义成char *orig_str = "Happy New Year, my dear friend!"。如果定义成指针形式,则指针指向一个字符串常量,存放在内存中的只读存储区,在GCC编译的时候,reverse_string()函数中头尾互换时,*string = *pstr会报段错误,因为*string和*pstr指针指向的这段内存是只读的,现在要改变他们的值,违背了指针操作内存的原则,所以会报段错误。

《The C programming language》第二版,5.5章94页有如下一段话:

     char amessage[] = "now is the time"; /* an array */
     char *pmessage = "now is the time"; /* a pointer */
amessage is an array, just big enough to hold the sequence of characters and '\0' that
initializes it. Individual characters within the array may be changed but amessage will always
refer to the same storage. On the other hand, pmessage is a pointer, initialized to point to a
string constant; the pointer may subsequently be modified to point elsewhere, but the result is
undefined if you try to modify the string contents.




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值