zoukankan      html  css  js  c++  java
  • C/C++指针参数赋值问题

      今天遇到一个问题,即在C/C++中,关于在函数里对指针赋值的问题。首先可以看到如下现象: 

    void test(int *p)
    {
        p = NULL;
    }
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        int *t , y = 10;
        t = &y;
        test(t);
    
        return a.exec();
    }
    

      

      这个结果令我有点吃惊,我一直以为传递指针,赋值完这个指针也会变的,没想到其实指针也是一个变量,我们如果要改变它,必须找到它在内存中的地址,也就是指针的地址。也就是说,对于函数中,如果对指针的地址进行赋值,事实上是改变不了原指针的!

      

    void test(int **p)
    {
        *p = NULL;
    }
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        int *t , y = 10;
        t = &y;
        test(&t);
    
        return a.exec();
    }
    

      

     另外,用引用赋值也可以解决这个问题:

    void test(int &p)
    {
        int n = 9;
        p = n;
    }
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        int t , y = 10;
        t = y;
        test(t);
    
        return a.exec();
    }
    

      

       另外,可以修改指针指向的内容,而不是修改指针地址,也可以改变内容。

      例子1:

    void test(int *p)
    {
        int n = 9;
        *p = n;
    }
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        int *t , y = 10;
        t = &y;
        test(t);
    
        return a.exec();
    }
    

      

       例子2:

    void test(int *p)
    {
        int n = 9;
        *p = n;
    }
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        int t , y = 10;
        t = y;
        test(&t);
    
        return a.exec();
    }
    

      

  • 相关阅读:
    nginx php-fpm 输出php错误日志
    图解phpstorm常用快捷键
    Mysq性能分析 —— Genral log(普通日志)与 Slow log(慢速日式)
    Mac Terminal
    Git安装与配置
    Linux ulimit
    tcpdump
    Linux 基础
    TCP
    HTTP
  • 原文地址:https://www.cnblogs.com/pinking/p/9339201.html
Copyright © 2011-2022 走看看