Chinaunix首页 | 论坛 | 博客
  • 博客访问: 907938
  • 博文数量: 84
  • 博客积分: 4334
  • 博客等级: 上校
  • 技术积分: 1610
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-27 07:49
文章分类

全部博文(84)

文章存档

2012年(5)

2011年(21)

2010年(58)

分类: C/C++

2010-11-29 17:23:50

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <string.h>
  4
  5 int main()
  6 {
  7 char *src="abcdefghijk";
  8 int len=strlen(src);
  9 char *dest = (char *)malloc(len+1);
 10
 11 char *a=&src[len-1];
 12 char *b=dest;
 13
 14 while(len-- != 0)
 15 *b++ = *a--;
 16 printf("%s\n",dest);
 17 free(dest);
 18 dest = NULL;
 19 return 0;
 20 }


运行情况:

第9句:

char *dest = (char *)malloc(len+1);<===>

char *dest = NULL;

dest = (char *)malloc(len+1);//字符串以\0结尾,因此也给\0分配一个字节空间,malloc的类型为void *,因此强制转换为char *类型。
 

第11,12句:

定义一个字符指针a,指向字符串src的最后一个字符k,定义一个字符指针b,指向dest


第15句:

*b++ = * a--;<==>等价于下面三句

1.*b = *a;

2. b++;

3. a--;


第16句:

想想为什么是返回dest,而不是b?


第17句:

防止内存泄露,在前面申请的内存空间现在都给他释放掉吧!


第18句:

释放掉内存后dest成了一个也指针,必须将其赋值为空。

阅读(12566) | 评论(0) | 转发(2) |
给主人留下些什么吧!~~