zoukankan      html  css  js  c++  java
  • 二级指针和函数参数——指针参数是如何传递内存的?

    1:如果函数的参数是一个指针,不要指望用该指针去申请动态内存。Test 函数的语句 GetMemory(str, 200)并没有使 str 获得期望的内存,str 依旧是 NULL,为什么?

    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");  // 运行错误   
    }   
    
    

     原因:

         毛病出在函数 GetMemory中。编译器总是要为函数的每个参数制作临时副本,指针参数 p 的副本是 _p,编译器使 _p =p。如果函数体内的程序修改了_p 的内容,就导致参数 p 的内容作相应的修改。这就是指针可以用作输出参数的原因。在本例中,_p 申请了新的内存,只是把_p 所指的内存地址改变了,但是 p 丝毫未变。所以函数 GetMemory并不能输出任何东西。事实上,每执行一次 GetMemory 就会泄露一块内存,因为没有用free 释放内存。 如果非得要用指针参数去申请内存,那么应该改用“指向指针的指针”。

    2:

    void GetMemory2(char **p, int num)   
    {   
        *p = (char *)malloc(sizeof(char) * num);   
    }  
    void Test2(void)   
    {   
         char *str = NULL;   
         GetMemory2(&str, 100); // 注意参数是 &str,而不是 str   
         strcpy(str, "hello");    
         cout<< str << endl;   
         free(str);    
    }   
    

     3:由于“指向指针的指针”这个概念不容易理解,我们可以用函数返回值来传递动态内存

    char *GetMemory3(int num)   
    {   
         char *p = (char *)malloc(sizeof(char) * num);   
         return p;   
    }  
    void Test3(void)   
    {   
         char *str = NULL;   
         str = GetMemory3(100);   
         strcpy(str, "hello");   
         cout<< str << endl;   
         free(str);    
    }   
    

      4:用函数返回值来传递动态内存这种方法虽然好用,但是常常有人把return 语句用错了。这里强调不要用return语句返回指向“栈内存”的指针,因为该内存在函数结束时自动消亡

    char *GetString(void)   
    {   
         char p[] = "hello world";   
         return p;  // 编译器将提出警告   
    }   
    void Test4(void)   
    {   
        char *str = NULL;   
        str = GetString(); // str 的内容是垃圾   
        cout<< str << endl;   
    }   
    

      5:用调试器逐步跟踪 Test4,发现执行 str = GetString 语句后 str 不再是 NULL 指针,但是 str 的内容不是“hello world”而是垃圾。

    char *GetString2(void)   
    {   
         char *p = "hello world";   
         return p;   
    }   
    void Test5(void)   
    {   
         char *str = NULL;   
         str = GetString2();   
         cout<< str << endl;   
    }   
    

      函数 Test5 运行虽然不会出错,但是函数 GetString2 的设计概念却是错误的。因为GetString2 内的“hello world”是常量字符串,位于静态存储区,它在程序生命期内恒定不变。无论什么时候调用 GetString2,它返回的始终是同一个“只读”的内存块。 

  • 相关阅读:
    Apache部署Django项目
    Docker
    常用算法
    Go之基本数据类型
    Go之流程控制
    Go基本使用
    Go安装与Goland破解永久版
    Linux
    详解java中的byte类型
    Linux统计文本中某个字符串出现的次数
  • 原文地址:https://www.cnblogs.com/dingou/p/5937024.html
Copyright © 2011-2022 走看看