首页 > 编程语言 > 详细

C语言学习之const

时间:2020-04-09 20:26:23      阅读:71      评论:0      收藏:0      [点我收藏+]
#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;
}

 

C语言学习之const

原文:https://www.cnblogs.com/weiyouqing/p/12669060.html

(1)
(1)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!