堆,栈,常量区,字符串等问题(二)

来源:互联网 发布:朱雀网络和小米的关系 编辑:程序博客网 时间:2024/05/17 12:25

上一篇学习地址
char *a 与char a[] 的区别
http://blog.csdn.net/qq_26437925/article/details/52136298


main(){    char*a[]={"work","at","alibaba"};    char**pa=a;    pa++;    printf("%s",*pa);}

这里写图片描述


void GetMemory(char *p, int num)   {       p = (char *)malloc(sizeof(char) * num);   }   void Test(void)   {       char *str = NULL;       GetMemory(str, 100);  // str 仍然为NULL       strcpy(str, "hello"); // 运行错误  }  

对比如下

void GetMemory(char **p, int num)   {       *p = (char *)malloc(sizeof(char) * num);   }   void Test(void)   {       char *str = NULL;       GetMemory(&str, 100);    strcpy(str, "hello");    printf("%s\n", str);    free(str);}  
形参  -》  实参 (值,指向)int a =》 int *a(要真正的改变a的值,用a的指针 *a)int *a =》 int **a(要真正改变a的指向,用*a的指针**a)

堆内存

char *GetMemory3(int num)   {       char *p = (char *)malloc(sizeof(char) * num);       return p; // 返回一个地址,地址是通过malloc而来的 函数返回后依然有效}  void Test3(void)   {       char *str = NULL;       str = GetMemory3(100);  // str指向了返回的一个地址(通过malloc是有效的)    strcpy(str, "hello");       printf("%s\n", str);    free(str);   } 

字符串:栈

char *GetStr()   {       char p[] = "hello"; // "hello"在栈上    return p; // 返回一个地址,地址栈上的,函数返回后栈被回收了}  void Test4(void)   {       char *str = NULL;       str = GetStr();  // str会指向一个不知道的地址      printf("%s\n", str); // 垃圾内容,不是hello} 

字符串:常量区

char *GetStr2()   {       char *p = "hello"; // "hello"在常量区, 静态区,只读的,生命周期不变    return p;}  void Test5(void)   {       char *str = NULL;       str = GetStr2(); // 始终得到的是同一个常量字符串    printf("%s\n", str); // hello} 

更多参考
找工作笔试面试那些事儿(3)—内存管理那些事
http://www.lai18.com/content/1989888.html

0 0