• C语言中的二级指针(双指针)


    原创作品,转载请标明出处http://blog.csdn.net/yming0221/article/details/7220688
    C语言更多查看

    二级指针又叫双指针。C语言中不存在引用,所以当你试图改变一个指针的值的时候必须使用二级指针。C++中可以使用引用类型来实现。

    下面讲解C中的二级指针的使用方法。

    例如我们使用指针来交换两个整型变量的值。

    错误代码如下:

    一级指针

    1. #include <stdio.h> 
    2.  
    3. void swap(int *a,int *b) 
    4.         int *tmp=NULL; 
    5.         tmp=a; 
    6.         a=b; 
    7.         b=tmp; 
    8.  
    9. int main(int argc,char **argv) 
    10.         int a=2; 
    11.         int b=3; 
    12.         printf("Before swap a=%d  b=%d ",a,b); 
    13.         swap(&a,&b); 
    14.         printf("After swap a=%d  b=%d ",a,b); 
    15.         return 0; 
    #include <stdio.h>
    
    void swap(int *a,int *b)
    {
            int *tmp=NULL;
            tmp=a;
            a=b;
            b=tmp;
    }
    
    int main(int argc,char **argv)
    {
            int a=2;
            int b=3;
            printf("Before swap a=%d  b=%d
    ",a,b);
            swap(&a,&b);
            printf("After swap a=%d  b=%d
    ",a,b);
            return 0;
    }
    
    输出的结构如下:

    结果分析:不论是数值还是指针,swap函数中的参数传递的是总是值,所以在上述函数中即使a和b的地址已参数传递给swap函数,而在函数内交换的是a和b的值(main函数中a的地址和b的地址),而交换完毕,函数相应的参数从栈中弹出,并不能返回给调用函数,所以该swap函数中的操作是徒劳。可怜

    这里完全可以直接交换a和b的值,不过如果a和b不是一个32位的整型变量,而是一个复杂的数据结构,这样做会降低效率。如下;

    1. void swap(TYPE *a,TYPE *b) 
    2.         TYPE tmp; 
    3.         tmp=*a; 
    4.         *a=*b; 
    5.         *b=tmp; 
    void swap(TYPE *a,TYPE *b)
    {
            TYPE tmp;
            tmp=*a;
            *a=*b;
            *b=tmp;
    }

    二级指针

    下面是使用二级指针分配内存的例子

    1. #include <stdio.h> 
    2. #include <stdlib.h> 
    3. #include <string.h> 
    4. void memorylocate(char **ptr) 
    5.         *ptr=(char *)malloc(10*sizeof(char)); 
    6. int main(int argc,char **argv) 
    7.         char *buffer; 
    8.         memorylocate(&buffer); 
    9.         strcpy(buffer,"12345"); 
    10.         printf("buffer %s ",buffer); 
    11.         return 0; 
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    void memorylocate(char **ptr)
    {
            *ptr=(char *)malloc(10*sizeof(char));
    }
    int main(int argc,char **argv)
    {
            char *buffer;
            memorylocate(&buffer);
            strcpy(buffer,"12345");
            printf("buffer %s
    ",buffer);
            return 0;
    }
    

    当想改变指针的值的时候不妨考虑使用二维指针。

  • 相关阅读:
    Common Words
    The end of other
    避免ssh断开导致运行命令的终止:screen
    Check iO:初学Python
    linux环境c++开发:ubuntu12.04使用llvm3.4.2
    boost库使用:仿SGI-STL实现的一个树节点allocator
    boost库使用:vs2013下boost::container::vector编译出错解决
    读论文系列:Nearest Keyword Search in XML Documents中使用的数据结构(CT、ECT)
    房产律师咨询
    E文阅读
  • 原文地址:https://www.cnblogs.com/kungfupanda/p/3685365.html
Copyright © 2020-2023  润新知