Chinaunix首页 | 论坛 | 博客
  • 博客访问: 655713
  • 博文数量: 150
  • 博客积分: 4070
  • 博客等级: 中校
  • 技术积分: 1795
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-23 21:44
文章分类

全部博文(150)

文章存档

2012年(1)

2011年(123)

2010年(26)

分类: C/C++

2011-06-21 16:12:40

例子1:
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>

  4. void GetMemory(char *p)
  5. {
  6.     p = (char *)malloc(100);
  7. }

  8. int main()
  9. {
  10.     char *str = NULL;
  11.     GetMemory(str);
  12.     strcpy( str, "hello world" );
  13.     printf(“%d\n”,str );
  14.     return 0;
  15. }
函数GetMemory并不能返回申请的内存,str的值仍然是NULL,GetMemory函数的指针参数p只是实参str的一个副本。
 
例子2:
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>

  4. char *GetMemory( )
  5. {
  6.     char p[] = "hello world";
  7.     return p;
  8. }

  9. int main()
  10. {
  11.     char *str = NULL;
  12.     str = GetMemory();
  13.     printf("%s\n",str);
  14.     return 0;
  15. }

函数GetMemory返回的是栈上的空间,它只在函数范围内有效,函数调用结束后,就会消失,因此也不能返回,输出的是乱码,也可能输出的hello world(但是并不能说明内存正常返回)。

例子3:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>

  4. void GetMemory( char **p, int num )
  5. {
  6.     *p = (char *) malloc( num );
  7. }

  8. int main()
  9. {
  10.     char *str = NULL;
  11.     GetMemory( &str, 100 );
  12.     strcpy( str, "hello");
  13.     printf("%s\n",str );
  14.     return 0;
  15. }

这种情况下能返回动态申请的内存。正常输出。

例子4:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>

  4. char *GetMemory(int num)
  5. {
  6.     char *p = (char *)malloc(num);
  7.     return p;
  8. }

  9. int main()
  10. {
  11.     char *str = NULL;
  12.     str = GetMemory(100);
  13.     strcpy(str, "hello");
  14.     printf("%s\n",str );
  15.     free(str);
  16.     return 0;
  17. }
GetMemory函数能返回动态申请内存,正常输出。
阅读(914) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~