zoukankan      html  css  js  c++  java
  • Linux C/C++基础——二级指针做形参

    1.二级指针做形参

      #include<stdio.h>                                                                                          
      #include<stdlib.h>
       
      void fun(int **temp)
      {
          *temp=(int*)malloc(sizeof(int));
          **temp=100;    //可以,但是变量前两个*不常见,常用下面这种
    //int *p=(int *)malloc(sizeof(int));
    //*p=100;
    //*temp=p;
    } int main() { int *p=NULL; fun(&p); printf("*p=%d ",*p); free(p);
    p=NULL;
    return 0; }

     

     2.值传递1

    #include <stdio.h>
    #include <stdlib.h>
    
    void fun(int *tmp)
    {
        tmp = (int *)malloc(sizeof(int));
        *tmp = 100;
    }
    
    int main(int argc, char *argv[])
    {
        int *p = NULL;
        fun(p); //值传递,形参修改不会影响实参
        printf("*p = %d
    ", *p);//err,操作空指针指向的内存
    
        return 0;
    }

     

     值传递2

      1 #include <stdio.h>                                                                                         
      2 #include <stdlib.h>
      3 
      4 void fun(int *tmp)
      5 {
      6     *tmp = 100;
      7 }
      8 int main(int argc, char *argv[])
      9 {
     10     int *p = NULL;
     11     p=(int *)malloc(sizeof(int));
     12     fun(p); //值传递,形参修改不会影响实参
     13     printf("*p = %d
    ", *p);
     14     free(p);
     15     p=NULL;
     16     return 0;
     17 }

     

     返回堆区地址

    #include <stdio.h>
    #include <stdlib.h>
    
    int *fun()
    {
        int *tmp = NULL;
        tmp = (int *)malloc(sizeof(int));
        *tmp = 100;
        return tmp;//返回堆区地址,函数调用完毕,不释放
    }
    
    int main(int argc, char *argv[])
    {
        int *p = NULL;
        p = fun();
        printf("*p = %d
    ", *p);//ok
    
        //堆区空间,使用完毕,手动释放
        if (p != NULL)
        {
            free(p);
            p = NULL;
        }
    
        return 0;
    }

     

    知识的二道贩子,此博客仅仅是个人学习总结!
  • 相关阅读:
    javascript 调试代码
    简洁的js拖拽代码
    搭个小窝
    FastDFS随笔
    JDK6和JDK7中String的substring()方法及其差异
    杂笔
    JVM内存随笔
    java中的final和volatile详解
    关于java的Synchronized,你可能需要知道这些(下)
    关于java的Synchronized,你可能需要知道这些(上)
  • 原文地址:https://www.cnblogs.com/xiangdongBig1/p/11904162.html
Copyright © 2011-2022 走看看