zoukankan      html  css  js  c++  java
  • C语言学习之const

    #include <stdio.h>
    #include <stdarg.h>
    
    typedef struct STest
    {
        char num;
    }stest_st, *stest_pst;
    
    
    int  main(int argn ,char *argv[])
    {
        const int iNum = 10;            //错误, const修饰iNum变量,其值不能修改
        iNum = 20;
    
        int const iNum2 = 30;            //错误, const修饰iNum变量,其值不能修改
        iNum2 = 40;
    
        const int * ptr1 = &iNum;        
        ptr1 = &iNum2;                    //正确, const修饰ptr1指向的对象,表示指向的对象的值不能修改,但是可以指向其他对象;
        *ptr1 = 50;                        //错误, ptr1指向的对象不能修改
    
        int const * ptr2 = &iNum;        
        ptr2 = &iNum2;                    //同上,正确
        *ptr2 = 60;                        //同上,错误
    
        int * const ptr3 = &iNum;        
        ptr3 = &iNum2;                    //错误, const修饰ptr3指针,表示不能修改为指向其他对象,但是其指向的对象可以被修改;
        *ptr3 = 70;                        //正确, 其指向的对象可以被修改;
        
        stest_st t;                        
        t.num = 80;
        const stest_pst ptrSt1;
        ptrSt1 = &t;                    //错误, 编译器认为stest_pst是一种类型,const直接修改的是变量ptrSt1, 因此此指针不能指向其他对象;
    
        const stest_pst ptrSt2 = (stest_pst)malloc(sizeof(stest_st));
        *ptrSt2 = t;                    //正确, ptrSt2指向的对象可以被修改;
        
        free(ptrSt2);
        return 0;
    }
  • 相关阅读:
    tomcat配置数据源
    Spring 配置详解
    典型的软件开发模型
    600字让你读懂Git
    JVM的自愈能力
    Maven的pom.xml文件详解
    如何使用Log4j
    掌握jQuery插件开发,这篇文章就够了
    CSS Gradient详解
    CSS Transition
  • 原文地址:https://www.cnblogs.com/weiyouqing/p/12669060.html
Copyright © 2011-2022 走看看