jeans chen
we've got them by the balls

http://blog.chinaunix.net/uid-20788517-id-34777.html

分类: C/C++

 

  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成了一个也指针,必须将其赋值为空。

posted on 2014-02-06 12:27  jeans chen  阅读(186)  评论(0编辑  收藏  举报